Skip to content

Instantly share code, notes, and snippets.

@sanjsanj
Created March 4, 2018 18:31
Show Gist options
  • Save sanjsanj/0363dae86d88e784ca71df6f066ddb09 to your computer and use it in GitHub Desktop.
Save sanjsanj/0363dae86d88e784ca71df6f066ddb09 to your computer and use it in GitHub Desktop.
// How to persist the React Redux state store to the browser's localStorage
// Code taken from Dan Abramov's video
// https://egghead.io/lessons/javascript-redux-persisting-the-state-to-the-local-storage
/**
localStorage.js
*/
export const loadState = () => {
try {
const serializedState = localStorage.getItem('state');
if (serializedState === null) {
return undefined;
}
return JSON.parse(serializedState);
} catch (error) {
return undefined;
}
};
export const saveState = (state) => {
try {
const serializedState = JSON.stringify(state);
localStorage.setItem('state', serializedState);
} catch (error) {
console.log(error);
}
};
/**
index.js
*/
import { loadState, saveState } from './localStorage';
const store = createStore(reducers, loadState());
store.subscribe(() => {
saveState(store.getState());
});
ReactDOM.render(
<Provider store={store}>
<App />
</Provider>,
document.getElementById('root'),
);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment