Skip to content

Instantly share code, notes, and snippets.

@ryanjyost
Last active May 7, 2019 16:43
Show Gist options
  • Select an option

  • Save ryanjyost/edbf4477be5e616bd9b18694f759a04e to your computer and use it in GitHub Desktop.

Select an option

Save ryanjyost/edbf4477be5e616bd9b18694f759a04e to your computer and use it in GitHub Desktop.
hydrateStateWithLocalStorage()
hydrateStateWithLocalStorage() {
// for all items in state
for (let key in this.state) {
// if the key exists in localStorage
if (localStorage.hasOwnProperty(key)) {
// get the key's value from localStorage
let value = localStorage.getItem(key);
// parse the localStorage string and setState
try {
value = JSON.parse(value);
this.setState({ [key]: value });
} catch (e) {
// handle empty string
this.setState({ [key]: value });
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment