question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Bug on NextJS hooks example when using react-apollo-hooks

See original GitHub issue

When using Material UI hooks with NextJS and react-apollo-hooks, received bug - TypeError: Cannot read property 'theme' of undefined at MyDocument.render (/material-ui/examples/nextjs-hooks-with-typescript/.next/server/static/development/pages/_document.js:156:38)

  • This is not a v0.x issue.
  • I have searched the issues of this repository and believe that this is not a duplicate.

Expected Behavior 🤔

Able to use Material UI hooks and Apollo hooks together.

Current Behavior 😯

undefined pageContext caused TypeError: Cannot read property 'theme' of undefined at line: https://github.com/ivawzh/material-ui/blob/fc6ae01e66bde4252a08903719a59ef108e05e5f/examples/nextjs-hooks-with-typescript/pages/_document.tsx#L14

image

Steps to Reproduce 🕹

I have prepared a repo here https://github.com/ivawzh/material-ui/commit/fc6ae01e66bde4252a08903719a59ef108e05e5f

Steps:

  1. git clone git@github.com:ivawzh/material-ui.git
  2. cd material-ui/examples/nextjs-hooks-with-typescript
  3. npm install && npm run dev
  4. In web browser, open http://localhost:3000/countries2
  5. See the error in your terminal

Context 🔦

I am trying to use Apollo hooks with Material UI hooks example. From the repo above you will see the non-hook Apollo endpoint at http://localhost:3000/countries is working fine as expected. But when Apollo hooks is in used, app will crash because pageContext becomes undefined.

Your Environment 🌎

https://github.com/ivawzh/material-ui/tree/fc6ae01e66bde4252a08903719a59ef108e05e5f/examples/nextjs-hooks-with-typescript

Tech Version
Material-UI v3.8.1
React 16.7.0-alpha.2
Browser Chrome
TypeScript 3.2.2
react-apollo 2.3.3
react-apollo-hooks 0.2.1

Issue Analytics

  • State:closed
  • Created 5 years ago
  • Comments:10 (6 by maintainers)

github_iconTop GitHub Comments

3reactions
oliviertassinaricommented, Mar 25, 2019

@ivawzh We are introducing a server-side rendering API: #15030. You can apply the same pattern now:

--- a/examples/nextjs-hooks-with-typescript/pages/_app.tsx
+++ b/examples/nextjs-hooks-with-typescript/pages/_app.tsx
@@ -39,12 +39,6 @@ class MyApp extends App <Props> {
             <Head>
               <title>My page</title>
             </Head>
-            {/* Wrap every page in Styles and Theme providers */}
-            <StylesProvider
-              generateClassName={this.pageContext.generateClassName}
-              sheetsRegistry={this.pageContext.sheetsRegistry}
-              sheetsManager={this.pageContext.sheetsManager}
-            >
               {/* ThemeProvider makes the theme available down the React
                   tree thanks to React context. */}
               <ThemeProvider theme={this.pageContext.theme}>
@@ -54,7 +48,6 @@ class MyApp extends App <Props> {
                     to render collected styles on server side. */}
                 <Component pageContext={this.pageContext} {...pageProps} />
               </ThemeProvider>
-            </StylesProvider>
           </ApolloHooksProvider>
         </ApolloProvider>
       </Container>
diff --git a/examples/nextjs-hooks-with-typescript/pages/_document.tsx b/examples/nextjs-hooks-with-typescript/pages/_document.tsx
index bb5ddad8c..a37a6f1bd 100644
--- a/examples/nextjs-hooks-with-typescript/pages/_document.tsx
+++ b/examples/nextjs-hooks-with-typescript/pages/_document.tsx
@@ -2,7 +2,8 @@ import { MuiThemeProviderProps } from '@material-ui/core/styles/MuiThemeProvider
 import Document, { AnyPageProps, Head, Main, NextScript, PageProps } from 'next/document';
 import React, { ComponentType } from 'react';
 import flush from 'styled-jsx/server';
-import { PageContext } from '../src/getPageContext';
+import getPageContext, { PageContext } from '../src/getPageContext';
+import { StylesProvider, ThemeProvider } from '@material-ui/styles';

 class MyDocument extends Document<{
   pageContext: MuiThemeProviderProps;
@@ -43,7 +44,7 @@ interface PagePropsWithPageContext extends AnyPageProps {
   pageContext: PageContext;
 }

-MyDocument.getInitialProps = ctx => {
+MyDocument.getInitialProps = async ctx => {
   // Resolution order
   //
   // On the server:
@@ -66,16 +67,17 @@ MyDocument.getInitialProps = ctx => {
   // 3. app.render
   // 4. page.render

-  // Render app and page and get the context of the page with collected side effects.
-  let pageContext: PageContext | undefined;
-  const page = ctx.renderPage((Component: ComponentType<PagePropsWithPageContext>) => {
-    const WrappedComponent: ComponentType<{ pageContext: PageContext } & PageProps> = props => {
-      pageContext = props.pageContext;
-      return <Component {...props} />;
-    };
+  const originalRenderPage = ctx.renderPage;
+  const pageContext = getPageContext();

-    return WrappedComponent;
-  });
+  ctx.renderPage = () =>
+    originalRenderPage({
+      enhanceApp: App => props => (<StylesProvider
+              sheetsRegistry={pageContext.sheetsRegistry}
+              sheetsManager={pageContext.sheetsManager}><App {...props} /></StylesProvider>),
+    });
+
+  const initialProps = await Document.getInitialProps(ctx);

   let css;
   // It might be undefined, e.g. after an error.
@@ -84,7 +86,7 @@ MyDocument.getInitialProps = ctx => {
   }

   return {
-    ...page,
+    ...initialProps,
     pageContext,
     // Styles fragment is rendered after the app and page rendering finish.
     styles: (

It fixes the problem on my end.

2reactions
oliviertassinaricommented, Jan 14, 2019

@ivawzh If you move the server-side queries to get getIntialProps, it’s not great but doable. Google Crawler stats are around 300ms of latency on our website (we index millions of pages). Ideally, we would like to see 100ms, it’s important for websites relying on SEO with a lot a lot a lot of pages. The DX is awesome, I think that it worth the tradeoff. I have nothing public if not the examples we have here.

Read more comments on GitHub >

github_iconTop Results From Across the Web

Bug on NextJS hooks example when using react-apollo-hooks
I am trying to use Apollo hooks with Material UI hooks example. From the repo above you will see the non-hook Apollo endpoint...
Read more >
Bug on integrating Material UI hooks and Apollo hooks - Stack ...
When using Material UI hooks (as its example shown here) with NextJS and react-apollo-hooks, received bug - TypeError: Cannot read property 'theme' of ......
Read more >
Hooks - Apollo GraphQL Docs
The ApolloProvider component leverages React's Context API to make a configured Apollo Client instance available throughout a React component tree.
Read more >
Understanding common frustrations with React Hooks
React Hooks can be frustrating despite their popularity and widespread use. Learn about some of the drawbacks to using React Hooks.
Read more >
Invalid Hook Call Warning - React
In order for Hooks to work, the react import from your application code needs to resolve to the same module as the react...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found