Skip to content

Instantly share code, notes, and snippets.

@jwill9999
Created February 26, 2017 00:35
Show Gist options
  • Save jwill9999/fa13a6d4315cc36bb0c659a2a6ea57f9 to your computer and use it in GitHub Desktop.
Save jwill9999/fa13a6d4315cc36bb0c659a2a6ea57f9 to your computer and use it in GitHub Desktop.
Persisting State to localStorage Redux React
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