-
Notifications
You must be signed in to change notification settings - Fork 57
Expand file tree
/
Copy pathuseLocalStorage.ts
More file actions
27 lines (24 loc) · 830 Bytes
/
useLocalStorage.ts
File metadata and controls
27 lines (24 loc) · 830 Bytes
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
type StoragePrimitive = string | boolean | number | undefined
type StorageArray = Array<StorageValue>
type StorageObject = { [key: string]: StorageValue }
type StorageValue =
| StoragePrimitive
| StorageArray
| StorageObject
export const useLocalStorage = <T = StorageValue>(key: string, defaultVal?: T): [data: T | undefined, setter: (val: T | undefined) => void] => {
const setter = (val: T | undefined) => {
if (val === undefined || val === null) {
localStorage?.removeItem(key)
} else {
localStorage?.setItem(key, JSON.stringify(val))
}
}
let storedVal = localStorage.getItem(key)
if (!storedVal) {
return [defaultVal, setter]
}
try {
return [JSON.parse(storedVal), setter]
} catch { }
return [defaultVal, setter]
}