7

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 {}

choz
  • 17,242
  • 4
  • 53
  • 73
Raphael Jayme
  • 115
  • 1
  • 6
  • `query` there refers to the query string in the url. E.g. `/yourTest?query=Hello`. Do I misunderstand something or you forget to provide more information into this? – choz Apr 01 '21 at 18:12
  • https://nextjs.org/docs/routing/dynamic-routes According to documentation query referrs to params like http://localhost:3000/Hello (router.query should've print { test: 'Hello' }) – Raphael Jayme Apr 01 '21 at 18:17
  • That is correct, however it will be an empty object during prerendering if the page doesn't have [data fetching requirement](https://nextjs.org/docs/basic-features/data-fetching). Might this be the case? – choz Apr 01 '21 at 18:19
  • It was it! Thanks a lot – Raphael Jayme Apr 01 '21 at 18:33

1 Answers1

12

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]);
choz
  • 17,242
  • 4
  • 53
  • 73
  • I'm seeing the same and the page is not a dynamic route though it does have some children from it. For example page is on /shop and there is also shop/checkout and shop/products but I am targeting shop/index – Crhistian Ramirez Apr 19 '22 at 19:33
  • Never mind, simply the fact that it has query parameters in the URL is another qualifier for it – Crhistian Ramirez Apr 19 '22 at 19:35