Skip to content

Instantly share code, notes, and snippets.

@NikaBuligini
Last active January 11, 2017 09:04
Show Gist options
  • Save NikaBuligini/6262d106f74b0096c6795b92416b3ef3 to your computer and use it in GitHub Desktop.
Save NikaBuligini/6262d106f74b0096c6795b92416b3ef3 to your computer and use it in GitHub Desktop.
Simple API for saving and retrieving data from local storage of browser
// returns object which is persisted in local storage
const getState = () => {
try {
const serializedState = localStorage.getItem('state');
if (serializedState === null) {
return undefined;
}
return JSON.parse(serializedState);
} catch (err) {
return undefined;
}
}
// overwrite new state
const saveState = (state) => {
try {
const serializedState = JSON.stringify(state);
localStorage.setItem('state', serializedState);
} catch (err) {
// do something with write error.
}
}
// example
const state = {
firstname: 'John',
lastname: 'Doe',
}
saveState(state);
// later
const storageData = getState();
console.log(storageData.firstname);
console.log(storageData.lastname);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment