Persisting Redux
A problem I ran into when I was developing a React Redux app was persisting my store. For some reason, when I refresh the page, React Redux actually did not persist.
I found two workarounds for this. One way was to simply push to localStorage
and pull from it when your app mounts.
Of course, that would be too easy and I wanted to challenge myself a bit more so I decided to use a library called redux-persist
.
This is my index.js
file in my React web app.
import React from 'react';import ReactDOM from 'react-dom';import './index.css';import App from './App.js';import { BrowserRouter } from 'react-router-dom';import { createStore } from 'redux';import { Provider } from 'react-redux';import rootReducer from './reducers/rootReducer';import { PersistGate } from 'redux-persist/integration/react';import { persistStore, persistReducer } from 'redux-persist';import storage from 'redux-persist/lib/storage';// const lawsonsStore = createStore(rootReducer);// redux-persistconst persistConfig = {key: 'root',storage}const persistedReducer = persistReducer(persistConfig, rootReducer);let lawsonsStore = createStore(persistedReducer);let persistor = persistStore(lawsonsStore);ReactDOM.render(<Provider store={lawsonsStore}><BrowserRouter><PersistGate loading={null} persistor={persistor}><App /></PersistGate></BrowserRouter></Provider>,document.getElementById('root'));
I had to wrap my app in the PersistGate
tag. I have to set loading
to null, something that I’m not sure what it does. And you have to tell it what to persist, and it seems like the convention is to name it persistor
.
Above that, you have to define an object called persistConfig
, with the key: 'root'
and storage
. I honestly am not sure what these do, as I just found it on StackOverflow and just copy/pasted the code.
Then you have to use a function called persistReducer(persistConfig, rootReducer)
. Then you have to create the store, like you would with regular redux, createStore(persistedReducer)
. Lastly, after you create the store, let persistor = persistStore(lawsonsStore)
persists the store you just created.
Now that you have redux-persist set up, one cool feature I found that my app does is that it keeps you logged in, even after you close the window and re-open it!! 😮
Stay safe out there. Wash your hands and maintain social distancing rules.