score:8

Accepted answer

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.

score:1

building on @cbdeveloper answer, here is example code running nextjs for getting the router data during client-side rendering:

filename: /pages/[...results].tsx

import { userouter } from 'next/router';
import { useeffect, usestate } from 'react';

export default function results() {
  const router = userouter();
  const { q } = router.query;

  const [searchquery, setsearchquery] = usestate("");

  useeffect(() => {
    console.log(`useeffect triggered`);
    router.isready ? setsearchquery(q as string) : console.log('router is not ready');
  },[q]);

  return (
    <>
      <p>q: {router.query.q}</p>
      <p>searchquery: {searchquery}</p>
      <p>bar: {router.query.bar}</p>

      <form>
        <label>search query:</label>
        <input
          type="text"
          name="q"
          value={searchquery}
          onchange={(e) => setsearchquery(e.target.value)}
        />
        <button type="submit">submit</button>
      </form>
    </>
  );
}

score:2

that's because nextjs works on both server side and client side and it becomes necessary to check if you are actually on the server or client by doing something like typeof window !== 'undefined' because the component needs to be hydrated on the client side.

when you use the userouter hook it runs only on the client side for obvious reasons, but when nextjs is delivering the "component" to the browser it has no idea what router.query.q refers to, it's only when the component gets hydrated on the client side the react hook kicks in and you can then retrieve the querystring

it is also similar to the reason why you would need to use dynamic importing in your nextjs app for most client side libraries.

p.s. i'm new nextjs myself, but i hope this made some sense.

score:3

this solution worked for me:

const router = userouter();
react.useeffect(() => {
  if (router.isready) {
    // code using query
    console.log(router.query);
   }
}, [router.isready]);

Related Query

More Query from same tag