Created
February 14, 2020 12:55
-
-
Save alan-ps/cd44e458844a6371e04b6f3adc8cc507 to your computer and use it in GitHub Desktop.
Persisting the State to the Local Storage
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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