Search code examples
javascriptreactjsreduxmiddlewareredux-persist

React Redux Persist


I just started to use Redux Persist, and for some reason I can't get it to work. (Cannot read property 'subscribe' of undefined error)

Persistor.js

import { createStore } from 'redux'
import { persistStore, persistReducer } from 'redux-persist'
import store from 'redux-persist/es/storage/session' // defaults to 
localStorage for web and AsyncStorage for react-native

import rootReducer from './reducers'

const persistConfig = {
    key: 'root',
    storage: store,
}

const persistedReducer = persistReducer(persistConfig, rootReducer)

export default () => {
   let store = createStore(persistedReducer)
   let persistor = persistStore(store)
   return { store: store, persistor: persistor }
}

index.js

import React from 'react';
import App from './components/App/App';
// import registerServiceWorker from './registerServiceWorker';
import { render } from 'react-dom'
import { createStore } from 'redux'
import { Provider } from 'react-redux'
import { PersistGate } from 'redux-persist/integration/react'
import persistor from './Persistor'
import rootReducer from './reducers'
import 'bootstrap/dist/css/bootstrap.min.css'
import './index.css'

render(
   <Provider store={persistor.persistor}>
      <PersistGate loading={null} persistor={persistor.store}>
         <App />
      </PersistGate>
   </Provider>,
   document.getElementById('root')
)

with normal Redux its worked properly. But as soon I tried to switch Persist Redux I got the error I write above.


Solution

  • The persistor value you are importing in index isn’t an object. It is a function that returns an object containing store and the persistor.

    Instantiate the persistor function and then also swap your values assigned to store in Provider with persistor in persistgate.

    Rename your import to something like configureStore to prevent any conflict.

    const { store, persistor } = configureStore()
    
    render(
       <Provider store={store}>
          <PersistGate loading={null} persistor={persistor}>
             <App />
          </PersistGate>
       </Provider>,
       document.getElementById('root')
    )