Last active
December 12, 2023 09:46
-
-
Save srvice-temp/046126458bbed2239e0b8d6403bced18 to your computer and use it in GitHub Desktop.
localStorage utility for typescript - keep track of types! π
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
// store objects and keep track of types with Window.localStorage | |
// (https://developer.mozilla.org/en-US/docs/Web/API/Window/localStorage) | |
interface Bar {} | |
export enum CacheKey { | |
Foo = 'Foo' | |
} | |
interface CacheValues { | |
[CacheKey.Foo]: Bar; | |
} | |
interface CacheUtil { | |
set: <T extends CacheKey>(key: T, object: CacheValues[T]) => void; | |
get: <T extends CacheKey>(key: T) => CacheValues[T]; | |
remove: (key: CacheKey) => void; | |
removeAll: () => void; | |
} | |
export const cacheUtil: CacheUtil = { | |
set: (key, object) => { | |
localStorage.setItem(key, JSON.stringify(object)); | |
}, | |
get: key => JSON.parse(localStorage.getItem(key) ?? {}), | |
remove: (key) => localStorage.removeItem(key), | |
removeAll: () => localStorage.clear(), | |
}; | |
// check out the following StackOverflow link for a collection of other useful localStorage functions | |
// https://stackoverflow.com/questions/34245593/html5-localstorage-useful-functions-javascript-typescript | |
JSON.parse expects a string. {}
is not a string. You need to use quotes
JSON.parse(localStorage.getItem(key) ?? "{}")
thank you for this!
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
why would you use
??
in line 25?JSON.parse('')
will throw an exception