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
41 lines (34 loc) · 1.29 KB
/
useLocalStorage.ts
File metadata and controls
41 lines (34 loc) · 1.29 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
35
36
37
38
39
40
41
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, (val: T | undefined) => void]
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: (val: T | undefined) => void] {
const value = deserialize(localStorage.getItem(key), defaultVal) ?? 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, defaultVal?: T): T | undefined {
if (!json) return undefined
try {
const stored = JSON.parse(json) || {}
Object.entries(defaultVal || {}).forEach(([k, v]) => {
if (stored[k] === undefined || stored[k] === null) {
stored[k] = v
}
})
return stored
} catch {
return undefined
}
}