-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlocalStorage.ts
More file actions
50 lines (41 loc) · 1.27 KB
/
localStorage.ts
File metadata and controls
50 lines (41 loc) · 1.27 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
42
43
44
45
46
47
48
49
50
import { useCallback, useEffect, useState } from "react";
export function useLocalStorage<T>(key: string, initialValue: T, callback?: (value: T) => void) {
const [storedValue, setStoredValue] = useState<T>(initialValue);
useEffect(() => {
try {
const item = window.localStorage.getItem(key);
if (!item || item == null) {
window.localStorage.setItem(key, JSON.stringify(initialValue));
setStoredValue(initialValue);
return;
}
setStoredValue(JSON.parse(item));
} catch (error) {
window.localStorage.setItem(key, JSON.stringify(initialValue));
setStoredValue(initialValue);
}
}, [key, storedValue, initialValue]);
useEffect(() => {
callback && callback(storedValue);
}, [storedValue, callback]);
/**
*
*
* @param value
*
*/
const setValue = useCallback(
(value: T | ((val: T) => T)) => {
try {
const valueToStore = value instanceof Function ? value(storedValue) : value;
setStoredValue(valueToStore);
if (typeof window !== "undefined")
window.localStorage.setItem(key, JSON.stringify(valueToStore));
} catch (error) {
console.error(error);
}
},
[key, storedValue],
);
return [storedValue, setValue] as const;
}