Created
August 21, 2018 15:17
-
-
Save LiamChapman/9e8e2b17fe877750137f7015b02ad8e0 to your computer and use it in GitHub Desktop.
Redux localStorage
This file contains hidden or 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
| // https://egghead.io/lessons/javascript-redux-persisting-the-state-to-the-local-storage | |
| export const loadState = () => { | |
| console.log( "State Loaded"); | |
| try { | |
| const serialisedState = localStorage.getItem('state'); | |
| if (serialisedState === null) { | |
| return undefined; | |
| } | |
| return JSON.parse( serialisedState ); | |
| } catch (err) { | |
| return undefined; | |
| } | |
| }; | |
| export const saveState = state => { | |
| console.log( "Saved state: ", state); | |
| try { | |
| const serialisedState = JSON.stringify(state); | |
| localStorage.setItem('state', serialisedState); | |
| } catch (err) { | |
| // Ignore write errors | |
| // Write to log? | |
| } | |
| }; | |
| /** | |
| * Example: | |
| **/ | |
| const initalState = loadState(); | |
| const store = configureStore(initalState); // configureStore custom function etc.. | |
| const unsubscribe = store.subscribe( saveState(store.getState()) ); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment