Created
August 25, 2021 05:47
-
-
Save jussikinnula/ff2564d3ae3560b63fded46b8520aba6 to your computer and use it in GitHub Desktop.
LocalStorage with basic types & JSON support
This file contains 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
const setItem = (key: string, value: any) => { | |
const payload: any = {}; | |
if (!value) { | |
payload.nullValue = true; | |
} else if (typeof value === 'number') { | |
payload.numberValue = Number(value); | |
} else if (typeof value === 'string') { | |
payload.stringValue = String(value); | |
} else { | |
payload.value = value; | |
} | |
localStorage.setItem(key, JSON.stringify(payload)); | |
}; | |
const getItem = (key: string) => { | |
const raw = localStorage.getItem(key); | |
try { | |
const { nullValue, numberValue, stringValue, value } = JSON.parse(raw); | |
if (nullValue) { | |
return null; | |
} | |
if (numberValue !== undefined) { | |
return numberValue; | |
} | |
if (stringValue !== undefined) { | |
return stringValue | |
} | |
return value; | |
} catch { | |
return raw; | |
} | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment