-
-
Save jgthms/02da257c1191e89479ae37d2433489ab to your computer and use it in GitHub Desktop.
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
// 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