Skip to content

Instantly share code, notes, and snippets.

@LiamChapman
Created August 21, 2018 15:17
Show Gist options
  • Select an option

  • Save LiamChapman/9e8e2b17fe877750137f7015b02ad8e0 to your computer and use it in GitHub Desktop.

Select an option

Save LiamChapman/9e8e2b17fe877750137f7015b02ad8e0 to your computer and use it in GitHub Desktop.
Redux localStorage
// 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