Middleware for Local Storage Synchronization
Present a middleware example that synchronizes specific parts of the Redux state to the local storage on every action dispatch, and initializes the state from local storage on store creation.
function loadState() {
try {
const serializedState = localStorage.getItem('state');
if (serializedState === null) {
return undefined;
}
return JSON.parse(serializedState);
} catch (err) {
return undefined;
}
}
This function tries to load the state saved in local storage. If the state does not exist or an error occurs, it returns undefined.
function saveState(state) {
try {
const serializedState = JSON.stringify(state);
localStorage.setItem('state', serializedState);
} catch (err) {
// Handle write errors, e.g., log the error message
}
}
This function saves the provided state to the local storage. Errors during save are caught and can be handled or logged.
const localStorageMiddleware = store => next => action => {
next(action);
saveState({
// Specify parts of the state to save to local storage.
specificPart: store.getState().specificPart
});
};
The middleware that saves specific parts of the state to local storage after every dispatched action.
const reHydrateStore = () => {
return loadState(); // Can be used to initialize the Redux store
};
Function to re-initialize the Redux store state from local storage if available.