Skip to content

Instantly share code, notes, and snippets.

@jgthms
Forked from sanjsanj/react-redux-localStorage.js
Created December 14, 2019 17:13
Show Gist options
  • Save jgthms/02da257c1191e89479ae37d2433489ab to your computer and use it in GitHub Desktop.
Save jgthms/02da257c1191e89479ae37d2433489ab 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