Next.js: With Apollo: Fetching client-side when using router.pathname

Created on 3 Nov 2017  路  5Comments  路  Source: vercel/next.js

  • [x] I have searched the issues of this repository and believe that this is not a duplicate.

Expected Behavior

I expected the data fetching to happen server-side on first load and be cached

Current Behavior

Data is fetched by the client (I see the network request) on first load

Steps to Reproduce (for bugs)

  1. Decorate an inner component (in my case, the header) with "withRouter"
  2. Use router.pathname.
    In my case const activeItem = router.pathname to set active item on menu
  3. Now, using the lib of the with-apollo example (initApollo and withData) data is fetched client-side.

If I remove that line everything is ok and I don't see any client-side fetching.

Thank you,
Matteo

Most helpful comment

If you're following the with-apollo example you'll need to include router in the context of getDataFromTree otherwise withRouter won't find the router in the context when rendering on the server.

I got it working using:

const url = { query: ctx.query, pathname: ctx.pathname, asPath: ctx.asPath }

try {
  await getDataFromTree(
    <ApolloProvider client={apollo}>
      <BaseComponent url={url} {...initialProps} />
    </ApolloProvider>,
    { router: url },
  )
} catch (error) {
  console.warn(error)
}

Notice how { router: url } is passed as the second argument to getDataFromTree

All 5 comments

@ads1018

If you're following the with-apollo example you'll need to include router in the context of getDataFromTree otherwise withRouter won't find the router in the context when rendering on the server.

I got it working using:

const url = { query: ctx.query, pathname: ctx.pathname, asPath: ctx.asPath }

try {
  await getDataFromTree(
    <ApolloProvider client={apollo}>
      <BaseComponent url={url} {...initialProps} />
    </ApolloProvider>,
    { router: url },
  )
} catch (error) {
  console.warn(error)
}

Notice how { router: url } is passed as the second argument to getDataFromTree

Thank you! It works! :)

@simenbrekken that's neat. I didn't know getDataFromTree accepted a second argument.

This thread has been automatically locked because it has not had recent activity. Please open a new issue for related bugs and link to relevant comments in this thread.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

sospedra picture sospedra  路  3Comments

YarivGilad picture YarivGilad  路  3Comments

irrigator picture irrigator  路  3Comments

havefive picture havefive  路  3Comments

knipferrc picture knipferrc  路  3Comments