-
Notifications
You must be signed in to change notification settings - Fork 105
Expand file tree
/
Copy pathindex.ts
More file actions
37 lines (32 loc) · 1.33 KB
/
index.ts
File metadata and controls
37 lines (32 loc) · 1.33 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
import type {UseStorageValueOptions, UseStorageValueResult} from '../useStorageValue/index.js';
import {useStorageValue} 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');
}
// eslint-disable-next-line @typescript-eslint/no-unsafe-type-assertion
return {value: undefined as Type, set: noop, remove: noop, fetch: noop};
};