-
Notifications
You must be signed in to change notification settings - Fork 11
/
Copy pathuseClientLocalStorage.ts
48 lines (42 loc) · 1.21 KB
/
useClientLocalStorage.ts
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
42
43
44
45
46
47
48
import { useCallback, useEffect, useState } from 'react';
export default function useClientLocalStorage<T extends number | string | boolean>(key: string, def?: T) {
const [value, setValue] = useState<T | undefined>();
useEffect(() => {
const storedValue = localStorage.getItem(key);
if (storedValue === null && def !== undefined) {
setValue(def);
} else if (storedValue !== null) {
switch (typeof def) {
case 'number':
setValue(parseFloat(storedValue) as T);
break;
case 'boolean':
setValue((storedValue === 'true') as T);
break;
default:
setValue(storedValue as T);
break;
}
}
}, [def, key]);
const _setValue = useCallback(
(_value: T) => {
let storageValue: string;
switch (typeof _value) {
case 'number':
storageValue = String(_value);
break;
case 'boolean':
storageValue = _value ? 'true' : 'false';
break;
default:
storageValue = _value as string;
break;
}
localStorage.setItem(key, storageValue);
setValue(_value);
},
[key],
);
return [value, _setValue] as const;
}