-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathmakeLocaleStorageValue.ts
More file actions
62 lines (54 loc) · 1.7 KB
/
Copy pathmakeLocaleStorageValue.ts
File metadata and controls
62 lines (54 loc) · 1.7 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
51
52
53
54
55
56
57
58
59
60
61
62
import { useCallback, useState } from 'react';
type Options<T> = {
serializer?: (value: T) => string;
deserializer?: (value: string) => T;
};
// Utility function to check if we are in a browser environment
const isBrowser = () => typeof window !== 'undefined';
export default function makeLocaleStorageValue<T>(
key: string,
options?: Partial<Options<T>>,
) {
const {
serializer: serialize = JSON.stringify,
deserializer: deserialize = JSON.parse,
} = options ?? {};
return function useLocaleStorageValue(): [T | null, (value?: T) => void] {
const readValueInLocalStorage = () => {
if (!isBrowser()) {
return null;
}
try {
const storedValue = localStorage.getItem(key);
return storedValue ? deserialize(storedValue) : null;
// eslint-disable-next-line @typescript-eslint/no-unused-vars
} catch (_) {
// eslint-disable-next-line no-console
console.error('Failed to parse value in localStorage', { key });
}
return null;
};
const [stateValue, setStateValue] = useState<T | null>(() =>
readValueInLocalStorage(),
);
const storeValue = useCallback((value?: T) => {
if (!isBrowser()) {
return;
}
try {
if (value) {
setStateValue(value);
localStorage.setItem(key, serialize(value));
} else {
setStateValue(null);
localStorage.removeItem(key);
}
// eslint-disable-next-line @typescript-eslint/no-unused-vars
} catch (_) {
// eslint-disable-next-line no-console
console.error('Failed to save value into localStorage', { key });
}
}, []);
return [stateValue, storeValue];
};
}