Skip to content

Instantly share code, notes, and snippets.

@ratbeard
Created January 14, 2019 17:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ratbeard/6b6e8ce13578df9b89e9f553ca09dd37 to your computer and use it in GitHub Desktop.
Save ratbeard/6b6e8ce13578df9b89e9f553ca09dd37 to your computer and use it in GitHub Desktop.
import { tryJsonParse } from "./tryJsonParse";
// Small wrapper around localStorage that converts to/from json.
//
// We also define all localStorage keys/values we store upfront here.
// This way all values are documented, and we get type saftey.
//
interface LocalStored {
device_info: string;
debugRedirects: boolean;
}
type LocalStoredKey = keyof LocalStored;
export function getItem<T extends LocalStoredKey>(key: T): LocalStored[T] | undefined {
const valueJson = window.localStorage.getItem(key)
if (valueJson) {
return tryJsonParse(valueJson)
} else {
return undefined
}
}
export function setItem<T>(key: LocalStoredKey, value: T) {
const valueJson = JSON.stringify(value)
window.localStorage.setItem(key, valueJson)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment