Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Next.js router is returning query parameters as undefined on first render?

I've got a page on my Next.js app that does the following:

  • It's a search page
  • The pathname is like: /search?q=search+slug
  • It loads data on the client
  • It needs to read the router.query to get the router.query.q value

PS: 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:

enter image description here

And then:

enter image description here

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?

like image 233
cbdeveloper Avatar asked Dec 21 '25 20:12

cbdeveloper


2 Answers

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 of useEffect methods 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.

like image 77
cbdeveloper Avatar answered Dec 23 '25 11:12

cbdeveloper


This solution worked for me:

const router = useRouter();
React.useEffect(() => {
  if (router.isReady) {
    // Code using query
    console.log(router.query);
   }
}, [router.isReady]);
like image 37
Jan Avatar answered Dec 23 '25 12:12

Jan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!