Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to persist redux state in the easiest way?

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.

like image 854
szczepaniakdominik Avatar asked Jan 29 '23 11:01

szczepaniakdominik


1 Answers

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());
});
like image 154
Tiago Alves Avatar answered Jan 31 '23 09:01

Tiago Alves