Middleware for LocalStorage Synchronization
Implement middleware that automatically saves and loads parts of the Redux state to and from LocalStorage, ensuring persistence across sessions.
function saveToLocalStorage(state) {
try {
const serializedState = JSON.stringify(state);
localStorage.setItem('state', serializedState);
} catch (e) {
console.warn('Unable to save state to localStorage.', e);
}
}
function loadFromLocalStorage() {
try {
const serializedState = localStorage.getItem('state');
if (serializedState === null) return undefined;
return JSON.parse(serializedState);
} catch (e) {
console.warn('Unable to load state from localStorage.', e);
return undefined;
}
}
Save and load functions for interacting with LocalStorage. 'saveToLocalStorage' saves a serialized version of the state to LocalStorage. 'loadFromLocalStorage' attempts to retrieve and parse the stored state.
const localStorageMiddleware = store => next => action => {
const result = next(action);
saveToLocalStorage(store.getState());
return result;
};
Middleware that captures every action dispatched to the store, then saves the updated state to LocalStorage.
const persistedState = loadFromLocalStorage();
const store = createStore(
rootReducer,
persistedState,
applyMiddleware(
localStorageMiddleware
// other middlewares can be added here
)
);
Creating a Redux store and initializing it with persisted state from LocalStorage, applying the middleware to automatically save the state.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Redux LocalStorage Middleware Example</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/redux/4.0.5/redux.min.js"></script>
<!-- Add other scripts like React, Redux-Thunk if needed -->
</head>
<body>
<!-- Your application HTML goes here -->
<script src="path/to/your/redux/store/and/middleware.js"></script>
</body>
</html>
A basic HTML template to include the Redux library and Redux store scripts. Set up your own application html and include the path to your store and middleware scripts.