I've got a page on my Next.js app that does the following:
/search?q=search+slugrouter.query to get the router.query.q valuePS: I'm using Redux
const dispatch = useDispatch();
const router = useRouter();
const query = router.query as { q: string };
const queryString = query.q;
console.log("SEARCH CONTAINER");
console.log(`queryString: ${queryString}`);
useEffect(() => {
dispatch(THUNK.LOAD(queryString));
return () => { dispatch(ACTION.RESET_STATE()); };
},[dispatch,queryString]);
See the useEffect. In theory is should run only once for every queryString (which is actually req.query.q).
But I was getting duplicated THUNK.LOAD actions. That's why I've added the console.log() there.
And this is what it's logging out:

And then:

And this is why I'm getting duplicated dispatches. Of course I can check for if (queryString) before dispatching, or maybe I can get it from window.location.search. But I am surprised the router.query.q comes as undefined on the first place. How is that even possible? Why would the req.query object be populated asynchronously? What is the explanation for this?
Just found out what is the solution to my problem:
From: https://nextjs.org/docs/api-reference/next/router#router-object
isReady:boolean- Whether the router fields are updated client-side and ready for use. Should only be used inside ofuseEffectmethods and not for conditionally rendering on the server.
This is what happens to the router.query on client when you hit /search?q=XXX.
1st render
router.isReady: false
router.query: {}
Subsequent renders
router.isReady: true
router.query: {"q":"xxx"}
Conclusion
The fact that router.query is not populated on the client (for SSG pages) on the first run is a design implementation detail. And you can monitor whether it's has been populated or not by checking the router.isReady boolean property.
This solution worked for me:
const router = useRouter();
React.useEffect(() => {
if (router.isReady) {
// Code using query
console.log(router.query);
}
}, [router.isReady]);
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