i'm trying to learn routing in Next.JS but I can't manage to get the query object.
File path: ./src/pages/[test]/index.tsx
import { useRouter } from 'next/router';
export default function Test() {
const router = useRouter();
console.log(router.query);
return (
<div>
<h1>Test</h1>
</div>
)
}
console.log just prints {}
If your page is a dynamic route, and you expect query to have route parameters in it, It is expected to have it empty during pre-rendering phase if your page is statically optimized by Automatic Static Optimization.
Quoting from documentation
Pages that are statically optimized by Automatic Static Optimization will be hydrated without their route parameters provided, i.e query will be an empty object ({}).
After hydration, Next.js will trigger an update to your application to provide the route parameters in the query object.
It is possible to watch the query in useEffect like following;
useEffect(() => {
console.log(router.query);
}, [router.query]);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With