32

When I am calling withRouter I am able to see the output when the data renders the second time.

My component looks like this:

const Home = (props) => {
  console.log("all props", props)
  let { router } = props
  let { category, item } = router.query
  console.log("Cat", category)
  console.log("Item", item)
  return (
    <FirebaseContext.Provider value={new Firebase()}>
      <div>
        <Head>
          <title>Category</title>
        </Head>
        <Navigation />
        {/* <Item category={category} item={item} {...props} /> */}
      </div>
    </FirebaseContext.Provider>
  )
}

Home.getInitialProps = async (props) => {
  console.log(props)
    return { req, query }
}

export default compose(withRouter, withAuthentication)(Home)

If you look at console, the very first render looks like:

asPath: "/c/cigars/1231"
back: ƒ ()
beforePopState: ƒ ()
events: {on: ƒ, off: ƒ, emit: ƒ}
pathname: "/c/[category]/[item]"
prefetch: ƒ ()
push: ƒ ()
query: {}

Why is query empty even though it clearly recognizes the asPath?

Thingamajig
  • 4,107
  • 7
  • 33
  • 61

3 Answers3

20

This might have something to do with Automatic Static Optimization

Next.js documentation says:

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 ({}).

Steric
  • 386
  • 4
  • 12
2

Is that withRouter from React Router?

If it is it will not add a query prop - it will add props called: location, history and match

Jonathan Irwin
  • 5,009
  • 2
  • 29
  • 48
0

I just fixed the issue by changing my own code. I move the router.query related code from constructor to render function. It seems because when refreshing page, the router.query is empty initially. After I put it in the render function, it will re-render the page after router.query is updated.

Sehrish Waheed
  • 1,230
  • 14
  • 17