Files
misode.github.io/src/app/hooks/useLocalStorage.ts
Misode d0bae089d1 Improve homepage (#245)
* Improve how generators are listed on home

* Add some icons for generators

* Remove debug

* Refactor cachedFetch and use generated changelogs

* Add limit to how many changes are shown by default

* Add more generator icons

* Refactor cards

* Fix generator icons for light theme

* Add more worldgen icons

* Add remaining generator icons

* Refactor navigation and badges style

* Group on homepage for guides and tools

* Fix header button style

* Add versions and technical changelog to homepage

* Make it clear that not all changes could be documented
2022-07-01 23:48:38 +02:00

36 lines
1.1 KiB
TypeScript

import { useCallback, useState } from 'preact/hooks'
type Result<T> = [T, (value: T | null | undefined) => void]
export function useLocalStorage(key: string, defaultValue: string): Result<string>
export function useLocalStorage<T>(key: string, defaultValue: T, parse: (s: string) => T, stringify: (e: T) => string): Result<T>
export function useLocalStorage<T>(key: string, defaultValue: T, parse?: (s: string) => T, stringify?: (e: T) => string): Result<T> {
const getter = useCallback(() => {
const raw = localStorage.getItem(key)
if (raw === null) {
return defaultValue
} else if (parse === undefined) {
return raw as unknown as T
} else {
return parse(raw)
}
}, [])
const [state, setState] = useState(getter())
const setter = useCallback((value: T | null | undefined) => {
if (value == null) {
localStorage.removeItem(key)
setState(defaultValue)
} else if (stringify !== undefined) {
localStorage.setItem(key, stringify(value))
setState(value)
} else {
localStorage.setItem(key, value as unknown as string)
setState(value)
}
}, [])
return [state, setter]
}