-
Notifications
You must be signed in to change notification settings - Fork 95
/
index.ts
43 lines (38 loc) · 1.24 KB
/
index.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
import {
useStorageValue,
type UseStorageValueOptions,
type UseStorageValueResult,
} from '../useStorageValue/index.js';
import {isBrowser, noop} from '../util/const.js';
let IS_LOCAL_STORAGE_AVAILABLE: boolean;
try {
IS_LOCAL_STORAGE_AVAILABLE = isBrowser && Boolean(globalThis.localStorage);
} catch {
IS_LOCAL_STORAGE_AVAILABLE = false;
}
type UseLocalStorageValue = <
Type,
Default extends Type = Type,
Initialize extends boolean | undefined = boolean | undefined,
>(
key: string,
options?: UseStorageValueOptions<Type, Initialize>
) => UseStorageValueResult<Type, Default, Initialize>;
/**
* Manages a single localStorage key.
*/
export const useLocalStorageValue: UseLocalStorageValue = IS_LOCAL_STORAGE_AVAILABLE ?
(key, options) => useStorageValue(localStorage, key, options) :
<
Type,
Default extends Type = Type,
Initialize extends boolean | undefined = boolean | undefined,
>(
_key: string,
_options?: UseStorageValueOptions<Type, Initialize>,
): UseStorageValueResult<Type, Default, Initialize> => {
if (isBrowser && process.env.NODE_ENV === 'development') {
console.warn('LocalStorage is not available in this environment');
}
return {value: undefined as Type, set: noop, remove: noop, fetch: noop};
};