Created
February 26, 2017 00:35
-
-
Save jwill9999/fa13a6d4315cc36bb0c659a2a6ea57f9 to your computer and use it in GitHub Desktop.
Persisting State to localStorage Redux React
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
import throttle from 'lodash/throttle'; | |
export const loadState = () => { | |
try { | |
const serializedState = localStorage.getItem('state'); | |
if(serializedState === null) ? return undefined : return JSON.parse(serializedState) | |
} | |
catch(err) { | |
return undefined | |
}; | |
export const saveState = state => { | |
try { | |
const serializedState = JSON.stringify(state); | |
localStorage.setItem('state', serializedState); | |
} | |
catch(err) { | |
//manage errors | |
console.log(err) | |
} | |
}; | |
/* | |
remember to subscribe to store and save State e.g only. Throttle prevents the localstorage being overly updated | |
and adding a callback timer limits this to every 1 sec | |
store.subscribe(throttle(() => { | |
saveState({ | |
todos: store.getState().todos | |
}); | |
},1000)); | |
const persistedState = loadState(); | |
const store = createStore( | |
todoApp, | |
persistedState | |
); | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment