forked from sheepzh/time-tracker-4-browser
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathuseLocalStorage.ts
More file actions
34 lines (28 loc) · 1.05 KB
/
Copy pathuseLocalStorage.ts
File metadata and controls
34 lines (28 loc) · 1.05 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
type StoragePrimitive = string | boolean | number | undefined
type StorageArray = Array<StorageValue>
type StorageObject = { [key: string]: StorageValue }
type StorageValue =
| StoragePrimitive
| StorageArray
| StorageObject
export function useLocalStorage<T>(key: string, defaultValue: T): [T, ArgCallback<T>]
export function useLocalStorage<T>(key: string): [T | undefined, (val: T | undefined) => void]
export function useLocalStorage<T = StorageValue>(key: string, defaultVal?: T): [data: T | undefined, setter: ArgCallback<T | undefined>] {
const value: T | undefined = deserialize(localStorage.getItem(key)) ?? defaultVal
const setter = (val: T | undefined) => {
if (val === undefined) {
localStorage.removeItem(key)
} else {
localStorage.setItem(key, JSON.stringify(val))
}
}
return [value, setter]
}
function deserialize<T>(json: string | null): T | undefined {
if (!json) return undefined
try {
return JSON.parse(json) as T
} catch {
return undefined
}
}