Last active
January 11, 2017 09:04
-
-
Save NikaBuligini/6262d106f74b0096c6795b92416b3ef3 to your computer and use it in GitHub Desktop.
Simple API for saving and retrieving data from local storage of browser
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
// 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