0

How to show content only after Redux Persist are loaded from offline store?

I have such code:

_app.jsx

const { store, persistor } = makeStore()

const App = pageProps => (
    <Provider store={store}>
        <PersistGate persistor={persistor}>
            <Head>
              ...
            </Head>
            <Header />
            <Body { ...pageProps } />
            <Footer />
        </PersistGate>
    </Provider>
)


export default appWithTranslation(App)

store.js

export default () => {
  const store = configureStore({
    reducer: persistReducer(
      {
        key: 'root',
        storage,
        whitelist: ['main', 'profile'],
      },
      reducer,
    ),
    middleware: (getDefaultMiddleware) => getDefaultMiddleware({
      serializableCheck: {
        ignoredActions: [FLUSH, REHYDRATE, PAUSE, PERSIST, PURGE, REGISTER],
      },
    }),
  });

  const persistor = persistStore(store);
  return { store, persistor };
};

[id].jsx

export default ({ id }) => {
    return (
        <div>
            { id }
        </div>
    )
}

export const getServerSideProps = async ({ query, locale }) => ({
    props: {
        id: query.id,
        ...await serverSideTranslations(locale, ['common']),
    },
})

In this case SSR doesn't work. Because of <PersistGate persistor={persistor}>. I try to fix it using:

<PersistGate persistor={persistor} loading={ <Body {...pageProps} /> }>

OR

<PersistGate persistor={ persistor } loading={ null }>
    { () => (
        <Body {...pageProps} />
    )

And SSR work! But.. I got Hydration failed, because of conflict default data and data in offline store.

So I found example for React without Next.JS how to render page only after getting offline data of Redux Persist. But I don't understand how to use it with Next.JS, if it possible.. :

https://github.com/rt2zz/redux-persist/issues/126

store.js

export default function configureStore() {
  // use desired middlewares
  const middlewares = [];

  return new Promise((resolve, reject) => {
    try {
      const store = createStore(
        rootReducer,
        undefined,
        compose(
          autoRehydrate(),
          applyMiddleware(...middlewares),
        ),
      );

      persistStore(
        store,
        { storage: localStorage },
        () => resolve(store)
      );
    } catch (e) {
      reject(e);
    }
  });
}

index.jsx

async function init() {
  const store = await configureStore();
  ReactDOM.render(
    <Provider store={store}>
      <Router />
    </Provider>,
    document.getElementById('root')
  );
}

init();

Any ideas?

Alex Poloz
  • 366
  • 7
  • 22

0 Answers0