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());
});
You can go to this tutorial Persisting Redux State . It is made by Dan Abmarov ( The man who made redux ). Just follow the steps and it will work for you.
For Quick answer :
Add a localstorage.js file in you project ( if you have separate redux folder, make this file there, or else just make it in src folder )
Paste this code in the file
export const loadState = () => {
try {
const serializedState = localStorage.getItem("state");
if (serializedState === null) {
return undefined;
}
return JSON.parse(serializedState);
} catch (err) {
return undefined;
}
};
export const saveState = (state) => {
try {
const serializesState = JSON.stringify(state);
localStorage.setItem("state", serializesState);
} catch (err) {
console.log(err);
}
};
const persistedState = loadState();
const Middlewares = [thunk];
const composeEnhancers = window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ || compose;
const store = createStore(
rootReducer,
persistedState,
composeEnhancers(applyMiddleware(...Middlewares))
);
store.subscribe(() => {
saveState(store.getState());
});
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.