I hope this is a simple question. I can't figure out why it's doing this. Anyways, using NextJS i'm trying to access the params in the router using the useRouter hook and combining it with the querystring plugin to split asPath, since NextJS doesn't allow you to access the query part of the router if using stateless. This is my code:
import { useRouter } from 'next/router';
import queryString from "query-string";
const withPageRouter = (router) => {
router.query = { ...queryString.parse(router.asPath.split(/\?/)[1]) };
return router;
};
function getRouterParams(){
const router = useRouter();
router = withPageRouter(router);
return router;
}
export async function getTown() {
const town = await getRouterParams();
return town;
}
NOw when I attempt to run it, I get this error:
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
lib/api.js (34:26) @ getRouterParams
32 |
33 | function getRouterParams(){
> 34 | const router = useRouter();
| ^
35 | router = withPageRouter(router);
36 | return router;
37 | }
But to me it looks like it should be fine; it is in a function body? I feel like i'm missing something obvious. I appreciate the help.
You can't be call useRouter() in normal function.
You can call only useRouter() inside of Top of the React function component or custom hooks
Learn more about Rules of Hooks here : https://reactjs.org/docs/hooks-rules.html