Created
January 14, 2019 17:24
-
-
Save ratbeard/6b6e8ce13578df9b89e9f553ca09dd37 to your computer and use it in GitHub Desktop.
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
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