Blog>
Snippets

Local storage synchronization middleware

Write middleware that synchronizes specific parts of the Redux state to the browser's local storage.
function localStorageMiddleware(store) {
  return function(next) {
    return function(action) {
      const result = next(action);
      const stateToSave = store.getState().specificPart; // Assuming 'specificPart' is the substate you want to persist
      localStorage.setItem('reduxState', JSON.stringify(stateToSave));
      return result;
    };
  };
}

// Add the middleware to your store during its creation:
// const store = createStore(
//   rootReducer,
//   applyMiddleware(localStorageMiddleware)
// );
This middleware intercepts every action that is dispatched to the store, passes the action to the next middleware or reducer, and then saves a specific part of the updated state to the local storage.
function loadState() {
  try {
    const serializedState = localStorage.getItem('reduxState');
    if (serializedState === null) {
      return undefined;
    }
    return JSON.parse(serializedState);
  } catch (err) {
    return undefined;
  }
}

// Usage while creating the store:
// const persistedState = loadState();
// const store = createStore(
//   rootReducer,
//   persistedState,
//   applyMiddleware(localStorageMiddleware)
// );
This utility function loads the persisted state from local storage when the application starts and catches any errors (e.g., invalid JSON) to prevent application crashes.
store.subscribe(() => {
  const stateToSave = store.getState().specificPart; // Again, specifying the part of the state to be saved
  localStorage.setItem('reduxState', JSON.stringify(stateToSave));
});
This is an alternative approach where you subscribe to the store changes and save the specific part of the state to local storage every time there is a change. This is less efficient than the middleware approach but is provided for completeness.