Last active
May 7, 2019 16:43
-
-
Save ryanjyost/edbf4477be5e616bd9b18694f759a04e to your computer and use it in GitHub Desktop.
hydrateStateWithLocalStorage()
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
| 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