urql icon indicating copy to clipboard operation
urql copied to clipboard

Wrapping nextjs _app with withUrqlClient

Open kysley opened this issue 7 years ago • 2 comments

Describe the issue Disclaimer: I'm new to nextjs/ssr, and I've read through #344 before writing this.

I'm following your guys' example when using a HOC to wrap each component, however I am looking to wrap the _app page, instead of having to inject each page individually.

I figured with the merging of #421 this would be possible as it also handles static optimization cases.

I first ran into an issue with line 21

...
withUrql.getInitialProps = async ({ AppTree }) => {
    // Run the wrapped component's getInitialProps function
    let appProps = {};

    if (App.getInitialProps) appProps = await App.getInitialProps(ctx); // <--- ctx is not defined!
...

I fixed that with

...
withUrql.getInitialProps = async (ctx) => {
    // Run the wrapped component's getInitialProps function
    let appProps = {};

    if (App.getInitialProps) appProps = await App.getInitialProps(ctx);
...

.. which works fine- great!

Now, when I wrap MyApp

class MyApp extends App {
  render() {
    const {Component, pageProps, urqlClient} = this.props
    console.log(this.props)
    return (
      <>
        <GlobalStyle />
        <Provider value={urqlClient}>
          <Layout>
            <Nav />
            <Component {...pageProps} />
          </Layout>
        </Provider>
      </>
    )
  }
}

export default withUrqlClient(MyApp)

Component is undefined and pageProps is a 404 status code.

I'm sure I'm missing something, or perhaps this is a limitation with next/urql, but any help would be amazing :)

kysley avatar Sep 23 '19 18:09 kysley

Hey @kysley

Choosing to wrap _app with getInitialProps does come with a trade-off since you will be opting out of static page optimization.

In this PR you can find our previous implementation that did just that.

PR: https://github.com/FormidableLabs/urql/pull/421/files Tree view: https://github.com/FormidableLabs/urql/tree/v1.5.0/examples/3-ssr-with-nextjs

JoviDeCroock avatar Sep 24 '19 13:09 JoviDeCroock

👋 @JoviDeCroock

Thanks for the response! I'll re-evaluate how often static page optimization would be used in my app and choose the appropriate implementation :)

I noticed you already have a PR that will contain a fix for ctx not being defined, but I can open a PR to fix the example.

kysley avatar Sep 24 '19 15:09 kysley