Created
February 12, 2022 16:21
-
-
Save gabrielh-silvestre/f2066a56e4dd4e33d8f03dd55b3a92fc to your computer and use it in GitHub Desktop.
Functions to work in Local Storage
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
function getInitialValue( | |
key: string, | |
defaultValue: any, | |
convertFromString = JSON.parse | |
) { | |
const localStorageValue = localStorage.getItem(key); | |
if (localStorageValue) { | |
try { | |
return convertFromString(localStorageValue); | |
} catch { | |
localStorage.removeItem(key); | |
} | |
} | |
return defaultValue; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment