0

I'm trying to create a simple routing test in a Next.js application using Dynamic Routes

As part of my test I have created pages/test/[id].js with the following code:

import { useRouter } from 'next/router'

export default function Test() {
    const router = useRouter()
    console.log(router)
    return <p />
}

However, when hitting the URL test/foo?a=1 I see the following in console:

ServerRouter {
  route: '/test/[id]',
  pathname: '/test/[id]',
  query: {},
  asPath: '/test/[id]',
  basePath: '',
  events: undefined,
  isFallback: false,
  locale: undefined,
  isReady: false,
  locales: undefined,
  defaultLocale: undefined,
  domainLocales: undefined,
  isPreview: false,
  isLocaleDomain: false
}

Question is, I'm expecting to see something here, particularly in query. What's missing here?

Neil Middleton
  • 22,105
  • 18
  • 80
  • 134
  • Might be related to [this](https://stackoverflow.com/questions/61040790/userouter-withrouter-receive-undefined-on-query-in-first-render) – LS_ Jun 09 '21 at 10:46

1 Answers1

1

You need your router to be ready (after page loaded) before trying to console log it.

You could wrap your console.log(router) inside a useEffect to prevent this behavior or even better, wait for it to be ready via, router.isReady inside your useEffect before trying to log it.

A recommandation I would have when trying to observe any kind of data (state, query...) is to wrap your console.log inside a useEffect instead of using it directly at top level.

If you want to log the router for example, each time it changes, you could put router inside brackets at the end of your useEffect, this will re-run what's inside your useEffect each time the value of router (or anything you want to put in there) changes!

Like this,

useEffect(() => {
    console.log(router)
}
,[router])
Dharman
  • 30,962
  • 25
  • 85
  • 135
feyndev
  • 122
  • 5