Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Higher-order versions the functions Dan Abramov demos in the Egghead series Building React Applications with Idiomatic Redux
/**
* Higher-order versions the functions Dan Abramov demos in the Egghead series:
* Building React Applications with Idiomatic Redux
* https://egghead.io/lessons/javascript-redux-persisting-the-state-to-the-local-storage
* https://github.com/gaearon/todos/blob/03-persisting-state-to-local-storage/src/localStorage.js
*/
export const createLoadStateFor = (storage) => () => {
try {
const serializedState = storage.getItem('state');
if (serializedState === null) {
return undefined;
}
return JSON.parse(serializedState);
} catch (err) {
return undefined;
}
};
export const createSaveStateFor = (storage) => (state) => {
try {
const serializedState = JSON.stringify(state);
storage.setItem('state', serializedState);
} catch (err) {
// Ignore write errors.
}
};
export const loadSessionState = createLoadStateFor(window.sessionStorage);
export const saveSessionState = createSaveStateFor(window.sessionStorage);
export const loadLocalState = createLoadStateFor(window.localStorage);
export const saveLocalState = createSaveStateFor(window.localStorage);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment