Reputation: 387
I am getting the 'Error: Invalid hook call' when I use a hook on my Next.js app. I can't figure out why I am getting this error as I thought it was being called inside a function component?
Server 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:
1. You might have mismatching versions of React and the renderer (such as React DOM)
2. You might be breaking the Rules of Hooks
3. You might have more than one copy of React in the same app
See https://reactjs.org/link/invalid-hook-call for tips about how to debug and fix this problem.
This error happened while generating the page. Any console logs will be displayed in the terminal window.
Source
pages/index.js (16:44) @ getStaticProps
14 |
15 | export const getStaticProps = async () => {
> 16 | const { data, loading, error } = useQuery(LINGO_QUERY);
| ^
17 |
18 | return {
19 | props: {
Check out my codesandbox here: https://codesandbox.io/s/empty-sea-hjunv
Upvotes: 2
Views: 1387
Reputation: 56
You can't use hook outside react component.
Then, in nextjs, getStaticProps
is a function used in server side context, and is pre-render at build time.
https://nextjs.org/docs/basic-features/data-fetching
Upvotes: 3
Reputation: 8332
You can't use hook outside component. Your getStaticProps
is not a component, its a function that you use to return props.
You can read more about it here: https://reactjs.org/warnings/invalid-hook-call-warning.html#breaking-the-rules-of-hooks
Just use that useQuery
hook in a component and use it to get some data and render it regularly.
You are probably executing that function somewhere as regular function.
To use hook you need to call it inside a component, and that is a rule because hooks may return some jsx and React made that as mandatory.
Upvotes: 1