Skip to content

Instantly share code, notes, and snippets.

@alan-ps
Created February 14, 2020 12:55
Show Gist options
  • Save alan-ps/cd44e458844a6371e04b6f3adc8cc507 to your computer and use it in GitHub Desktop.
Save alan-ps/cd44e458844a6371e04b6f3adc8cc507 to your computer and use it in GitHub Desktop.
Persisting the State to the Local Storage
// See: https://egghead.io/lessons/javascript-redux-persisting-the-state-to-the-local-storage
const loadState = () => {
try {
const serializedState = localStorage.getItem('state');
if (serializedState === null) {
return undefined;
}
return JSON.parse(serializedState);
} catch (err) {
return undefined;
}
}
const saveState = (state) => {
try {
const serializedState = JSON.stringify(state);
localStorage.setItem('state', serializedState);
} catch (err) {
// Ignore write errors.
}
}
const persistedState = loadState();
const store = createStore(
todoApp,
persistedState
);
store.subscribe(() => {
saveState({
todos: store.getState().todos
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment