-
-
Notifications
You must be signed in to change notification settings - Fork 3.2k
/
Copy pathuseSessionStorage.ts
45 lines (40 loc) · 1.34 KB
/
useSessionStorage.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
import { useEffect, useState } from 'react';
import { isBrowser } from './misc/util';
const useSessionStorage = <T>(
key: string,
initialValue?: T,
raw?: boolean
): [T, (value: T) => void] => {
if (!isBrowser) {
return [initialValue as T, () => {}];
}
// eslint-disable-next-line react-hooks/rules-of-hooks
const [state, setState] = useState<T>(() => {
try {
const sessionStorageValue = sessionStorage.getItem(key);
if (typeof sessionStorageValue !== 'string') {
sessionStorage.setItem(key, raw ? String(initialValue) : JSON.stringify(initialValue));
return initialValue;
} else {
return raw ? sessionStorageValue : JSON.parse(sessionStorageValue || 'null');
}
} catch {
// If user is in private mode or has storage restriction
// sessionStorage can throw. JSON.parse and JSON.stringify
// can throw, too.
return initialValue;
}
});
// eslint-disable-next-line react-hooks/rules-of-hooks
useEffect(() => {
try {
const serializedState = raw ? String(state) : JSON.stringify(state);
sessionStorage.setItem(key, serializedState);
} catch {
// If user is in private mode or has storage restriction
// sessionStorage can throw. Also JSON.stringify can throw.
}
});
return [state, setState];
};
export default useSessionStorage;