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.

with-redux-persist SSR issue

See original GitHub issue

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

Issue Analytics

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

github_iconTop GitHub Comments

42reactions
nuriuncommented, Jun 22, 2020

@jeffersoncustodio820 Your solution is good, but this causes ReactDOM.hydrate to throw an HTML mismatch error.

Here, this is my solution either:

This is able to work on the server and client side. Also, since it works the same way on both sides, so we don’t annoy the hydrate function for HTML mismatch error.

<PersistGate loading={null} persistor={persistor}>
    {() => (
        <ThemeProvider theme={{}}>
            <EverythingElse />
        </ThemeProvider>
    )}
</PersistGate>

So, how?

Because, as you can see below, PersistGate defines this.state.bootstrapped’s value while componentDidMount work. However, componentDidMount doesn’t work on the server-side. Also, it means you can not use redux-persist on the server-side.

  componentDidMount() {
    this._unsubscribe = this.props.persistor.subscribe(
      this.handlePersistorState
    )
    this.handlePersistorState()
  }

  handlePersistorState = () => {
    const { persistor } = this.props
    let { bootstrapped } = persistor.getState()
    if (bootstrapped) {
      if (this.props.onBeforeLift) {
        Promise.resolve(this.props.onBeforeLift())
          .finally(() => this.setState({ bootstrapped: true }))
      } else {
        this.setState({ bootstrapped: true })
      }
      this._unsubscribe && this._unsubscribe()
    }
  }

If we passed a function as a child, we can return our component directly according to the code below. In this scenario, the status of this.state.bootstrapped is not important.

  render() {
    if (process.env.NODE_ENV !== 'production') {
      if (typeof this.props.children === 'function' && this.props.loading)
        console.error(
          'redux-persist: PersistGate expects either a function child or loading prop, but not both. The loading prop will be ignored.'
        )
    }
    if (typeof this.props.children === 'function') {
      return this.props.children(this.state.bootstrapped)
    }

    return this.state.bootstrapped ? this.props.children : this.props.loading
  }
16reactions
Pushplaybangcommented, Apr 6, 2020

Pretty disappointed to find this closed without a clear response.

Read more comments on GitHub >

github_iconTop Results From Across the Web

Using redux with redux-persist with server-side rendering
When you use Redux-persist with SSR, It creates crashes, problems like It shows you white screen for 1-5 seconds and then shows the...
Read more >
How to setup store and Redux Persist with Next.js for SSR
The principle of Redux Persist is to make your Store persist after reloading a page and to keep this data afterwards when the...
Read more >
React SSR Persist Redux data - Medium
When you are using redux-persist with the default configuration, means you are storing your data on browser storage and you don't have a...
Read more >
Using redux with redux-persist with server-side rendering ...
When you use Redux-persist with SSR, It creates crashes, problems like It shows you white screen for 1-5 seconds and then shows the...
Read more >
Persist state with Redux Persist using Redux Toolkit in React
When we refresh the browser, our data will be lost. Let's learn how to use Redux Persist to save the state in persistent...
Read more >

github_iconTop Related Medium Post

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