I tried to implement Redux-Persist and this is the code I wrote:
import { createStore, combineReducers } from 'redux';
import { usersReducer } from './users';
import { eventsReducer } from './events';
import { persistStore, persistReducer } from 'redux-persist';
import storage from 'redux-persist/lib/storage';
const persistConfig = {
key: 'root',
storage
}
const reducer = combineReducers({ users: usersReducer, events: eventsReducer })
const persistedReducer = persistReducer(persistConfig, reducer);
const store = createStore(persistedReducer);
const persistor = persistStore(store);
export { store, persistor };
My store.js file:
import { createStore, combineReducers } from 'redux';
import { usersReducer } from './users';
import { eventsReducer } from './events';
import { persistStore, persistReducer } from 'redux-persist';
import storage from 'redux-persist/lib/storage';
const persistConfig = {
key: 'root',
storage
}
const reducer = combineReducers({ users: usersReducer, events: eventsReducer })
const persistedReducer = persistReducer(persistConfig, reducer);
const store = createStore(persistedReducer);
const persistor = persistStore(store);
export { store, persistor };
My usersReducer.js file (eventsReducer.js is built like this one):
const initialState = {
loggedIn: false,
thisUser: []
}
export function usersReducer(state = initialState, action) {
switch (action.type) {
case 'users/loggedIn':
return { ...state, loggedIn: action.payload }
case 'users/addUser':
return { ...state, thisUser: action.payload[0] }
case 'users/setActivated':
return { ...state, thisUser: { ...state.thisUser, activated: action.payload } }
case 'clearAll':
return {
thisUser: []
}
default:
return state
}
}
My index.js file:
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import { Provider } from 'react-redux'
import { store, persistor } from './store/store';
import { PersistGate } from 'redux-persist/integration/react'
ReactDOM.render(
<Provider store={store}>
<PersistGate persistor={persistor}>
<App />
</PersistGate>
</Provider>,
document.getElementById('root')
);
My problem is: Redux-Persist works and is saved in localStorage, but when I refresh the page, my data saved in localStorage with Redux-Persist don't update my local state and will be empty. I think that on any refresh of the page I should get persisted data from localStorage and send back into my Redux state.
I don't know if is correct what I say but I need help how to resolve this problem.