简体   繁体   中英

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.

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 :

  1. 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 )

  2. 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);
  }
};
  1. Here I have stored the state in the local storage, you can also store it in cookie to make it inaccessible by the user.
  2. Then if you are creating store in index.js file, call loadState and pass it as initial state in the createStore function. I have made separate store file so my code is a little different
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());
});
  1. And that's all. You are done. Go to the browser and reload as many times you can.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM