Blog>
Snippets

Implementing Middleware for Local Storage Data Persistence

Develop a middleware function that saves and loads the application state to and from the local storage, handling changes in Redux middleware.
function saveToLocalStorage(state) {
  try {
    const serializedState = JSON.stringify(state);
    localStorage.setItem('state', serializedState);
  } catch (e) {
    console.error('Could not save state to localStorage:', e);
  }
}
This function takes the application state, serializes it into a JSON string, and saves it to the browser's localStorage under the key 'state'. If an error occurs, it logs the error to the console.
function loadFromLocalStorage() {
  try {
    const serializedState = localStorage.getItem('state');
    if (serializedState === null) return undefined;
    return JSON.parse(serializedState);
  } catch (e) {
    console.error('Could not load state from localStorage:', e);
    return undefined;
  }
}
This function attempts to load the serialized application state from localStorage, parse it as JSON, and return it. If no state is stored, or an error occurs, it logs the error to the console and returns undefined.
const localStorageMiddleware = store => next => action => {
  const result = next(action);
  saveToLocalStorage(store.getState());
  return result;
};
This is a middleware for Redux that intercepts actions dispatched to the store, let's them proceed to the reducers and then, right after the state has been updated by the reducers, saves the new state to the local storage.
const reHydrateStore = () => {
  const serializedState = localStorage.getItem('state');
  if (serializedState === null) return undefined;
  return JSON.parse(serializedState);
};
This function is meant to be used at the application initialization time, to rehydrate the store with the state saved in the local storage if available.