I need to persist state in Redux after refresh of my website. What is the easiest way to do this? I rather wouldn't like to use redux-persist if it possible.
Basically, you need two functions, loadState() and saveState().
export const loadState = () => {
try {
const serializedState = localStorage.getItem("state");
if (!serializedState) return undefined;
else return JSON.parse(serializedState);
} catch(err) {
return undefined;
}
};
export const saveState = (state) => {
try {
const serializedState = JSON.stringify(state);
localStorage.setItem("state", serializedState);
} catch(err) {
console.log(err);
}
};
You need the try/catch due some privacy settings on browsers.
Then, you have to call loadState
when you are initializing your store and call saveState
on store.subscribe()
to save the state to localStorage on every state change. Like this:
const persistedStore = loadState();
const store = createStore(
// ... your reducers
persistedStore
);
store.subscribe(() => {
saveState(store.getState());
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With