Skip to content

with-redux-persist SSR issue #8240

Closed
Closed
@iamalvisng

Description

Example bug report

Example name

with-redux-persist

Describe the bug

A clear and concise description of what the bug is.
Implementing with-redux-persist leads to HTML elements missing from the page source.

To Reproduce

  1. In _app.js
  2. Wrap the components with <Provider> and <PersistGate>

_app.js

render() {
    const { Component, pageProps, reduxStore } = this.props;

    return (
      <Container>
        <AppPageHead />
        <GlobalStyle />
        <Provider store={reduxStore}>
          <PersistGate loading={null} persistor={this.persistor}>
            <Layout>
              <Component {...pageProps} {...this.state} />
            </Layout>
          </PersistGate>
        </Provider>
      </Container>
    );
}

test.js

import React from 'react';

export default () => <div> Hello world</div>;

with-redux-store.js

import React from 'react';
import { initializeStore } from '../store';

const isServer = typeof window === 'undefined';
const __NEXT_REDUX_STORE__ = '__NEXT_REDUX_STORE__';

function getOrCreateStore(initialState) {
  // Always make a new store if server, otherwise state is shared between requests
  if (isServer) {
    return initializeStore(initialState);
  }

  // Create store if unavailable on the client and set it on the window object
  if (!window[__NEXT_REDUX_STORE__]) {
    window[__NEXT_REDUX_STORE__] = initializeStore(initialState);
  }
  return window[__NEXT_REDUX_STORE__];
}

export default App =>
  class AppWithRedux extends React.Component {
    static async getInitialProps(appContext) {
      // Get or Create the store with `undefined` as initialState
      // This allows you to set a custom default initialState
      const reduxStore = getOrCreateStore();

      // Provide the store to getInitialProps of pages
      appContext.ctx.reduxStore = reduxStore;

      let appProps = {};
      if (typeof App.getInitialProps === 'function') {
        appProps = await App.getInitialProps(appContext);
      }

      return {
        ...appProps,
        initialReduxState: reduxStore.getState(),
      };
    }

    constructor(props) {
      super(props);
      this.reduxStore = getOrCreateStore(props.initialReduxState);
    }

    render() {
      return <App {...this.props} reduxStore={this.reduxStore} />;
    }
  };

Expected behavior

  1. SSR to work as expected

Screenshots

Before
Screen Shot 2019-08-05 at 10 51 38 AM

After
Screen Shot 2019-08-05 at 10 52 52 AM

System information

  • OS: macOS
  • Browser chrome
  • Version of Next.js: 9.0.2

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions