-
-
Notifications
You must be signed in to change notification settings - Fork 12
/
hooks.ts
49 lines (43 loc) · 1.21 KB
/
hooks.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
49
import {
Dispatch,
useEffect,
useState,
SetStateAction,
useCallback,
} from 'react';
import isEqual from 'lodash.isequal';
import {
getBrowserStorageValue,
setBrowserStorageValue,
Store,
} from './storage';
export function useBrowserStorageState<K extends keyof Store>(
key: K,
initialValue: Store[K]
): [Store[K], Dispatch<SetStateAction<Store[K]>>, boolean] {
const [state, setState] = useState(initialValue);
const [isLoading, setIsLoading] = useState(true);
useEffect(() => {
async function getBrowserStorageState() {
setIsLoading(true);
const value = await getBrowserStorageValue(key);
value !== undefined &&
setState((prevState) =>
isEqual(prevState, value) ? prevState : value
);
}
getBrowserStorageState()
.catch(console.error)
.finally(() => setIsLoading(false));
}, [key]);
const setBrowserStorageState = useCallback(
(value: SetStateAction<Store[K]>) =>
setState((prevState) => {
const newValue = value instanceof Function ? value(prevState) : value;
setBrowserStorageValue(key, newValue);
return newValue;
}),
[key]
);
return [state, setBrowserStorageState, isLoading];
}