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.

React Context Provider in _app.js doesn't work in _document.js

See original GitHub issue

Bug report

I put a React Context Provider in my custom _app.js, and used the context in my pages. This resulted in undefined context in SSR.

Describe the bug

_app.js

import React, { Fragment } from 'react';
import { Modal } from '@redq/reuse-modal';
import '@redq/reuse-modal/es/index.css';
import { MyProvider } from '../../common/src/contexts/MyContext';

export default ({ Component, pageProps }) => {
  return (
    <Fragment>
      <Modal />
      <MyProvider>
        <Component {...pageProps} />
      </MyProvider>
    </Fragment>
  );
};

_document.js

import Document, { Head, Main, NextScript } from 'next/document';
import { ServerStyleSheet } from 'styled-components';
import FavIcon from 'common/src/assets/image/favicon.png';

export default class CustomDocument extends Document {
  static async getInitialProps(ctx) {
    const sheet = new ServerStyleSheet();
    const originalRenderPage = ctx.renderPage;

    try {
      ctx.renderPage = () =>
        originalRenderPage({
          enhanceApp: App => props => sheet.collectStyles(<App {...props} />),
        });

      const initialProps = await Document.getInitialProps(ctx);
      return {
        ...initialProps,
        styles: (
          <>
            {initialProps.styles}
            {sheet.getStyleElement()}
          </>
        ),
      };
    } finally {
      sheet.seal();
    }
  }
  render() {
    return (
      <html lang="en">
        <Head>
          <link rel="shortcut icon" type="image/x-icon" href={FavIcon} />
        </Head>
        <body>
          <Main />
          <NextScript />
        </body>
      </html>
    );
  }
}

Error message: TypeError: Cannot read property ‘value’ of undefined

ctx.renderPage
./pages/_document.js:11
   8 |    const originalRenderPage = ctx.renderPage;
   9 | 
  10 |    try {
> 11 |      ctx.renderPage = () =>
     | ^  12 |        originalRenderPage({
  13 |          enhanceApp: App => props => sheet.collectStyles(<App {...props} />),
  14 |        });

Issue Analytics

  • State:closed
  • Created 4 years ago
  • Reactions:2
  • Comments:8 (6 by maintainers)

github_iconTop GitHub Comments

1reaction
IAmNatchcommented, Jun 29, 2019

@frol I’ve been searching all day for a solution to this problem and finally your post saved me.

I was running styled-components and it ran perfectly on dev, but would never show my themes in “prod” mode. I updated to v8.1.1-canary.62, with styled components at 4.3.2.

Made my day thanks.

1reaction
frolcommented, Jun 11, 2019

It turned out that my issue was reported in #7167 and fixed in #7200 (which is only available in the 8.1.1 [canary] build)

Read more comments on GitHub >

github_iconTop Results From Across the Web

React Context Provider in _app.js doesn't work in _document.js
Bug report. I put a React Context Provider in my custom _app. js, and used the context in my pages. This resulted in...
Read more >
I can't see why my context api does not work in reactjs
i wrapped the index.js file with the Provider wrapper as follows: import ReactDOM from 'react-dom/client' ...
Read more >
Context - React
A React component that subscribes to context changes. Using this component lets you subscribe to a context within a function component. Requires a...
Read more >
How to Work with the React Context API - Toptal
This new API solves one major problem–prop drilling. Even if you're not familiar with the term, if you've worked on a React.js app,...
Read more >
Provider | React Redux
Could not find "store" in the context of "Connect(MyComponent)". Either wrap the root component in a <Provider> , or pass a custom 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