I'm new to react/next and I'm trying to load my post with getStaticProps, the problem is if I use the "useAppContext" or even "useContext(AppContext)"
error - Error: Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons:
- You might have mismatching versions of React and the renderer (such as React DOM)
- You might be breaking the Rules of Hooks
- You might have more than one copy of React in the same app
If I use this "useContext" inside of the body of my function component it indeed loads correctly but how could I retrieve the id of the post on my getStaticProps function?
My actual code:
import { GetStaticPaths, GetStaticProps } from 'next';
import { useAppContext } from '../../context/AppContext';
interface PostProps {
post: {
field_body: string,
field_description: string,
field_posts_tags: string,
nid: string,
title: string,
field_readingtime: string
}
}
export default function PostTemplate({post}: PostProps) {
console.log(post);
return (
<h2>test</h2>
)
}
export const getStaticPaths: GetStaticPaths = async() => {
return {
paths: [],
fallback: true
}
}
export const getStaticProps: GetStaticProps = async () => {
const value = useAppContext();
const postNid = value.postNid;
const post = await fetch(`https://cms.jonasdev.com.br/api/posts/get/${postNid}`)
.then(response => response.json())
.then(response => response[0])
return {
props: {
post
},
revalidate: 60 * 60 * 24 //24h
}
}
Since I could not find a way to use context inside of getStaticProps I changed how I handle the get request - now I'm no longer using the post id (postNid) but the slug (e.g /using-multiple-deploy-keys) to query the full data of the post. Since I'm no longer using context I was able to use getStaticProps to fetch the data.
For reference, the commits here (https://github.com/jonas-gerosa361/jonasdev/commits/main) on March 10th cover this change in detail.