forked from ionic-team/ionic-docs
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlocal-storage.ts
More file actions
48 lines (41 loc) · 1.12 KB
/
Copy pathlocal-storage.ts
File metadata and controls
48 lines (41 loc) · 1.12 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
function getItem(key: string): string {
try {
return localStorage.getItem(key);
} catch (error) {
console.warn(`Unable to get key "${key}" from localStorage:`, error);
return null;
}
}
function setItem(key: string, value: string): string {
try {
if (localStorage.getItem(key) === value) {
return value;
}
localStorage.setItem(key, value);
notify(key, value);
return value;
} catch (error) {
console.warn(`Unable to set key "${key}" of localStorage:`, error);
return null;
}
}
function notify(key: string, value: string) {
if (window && typeof window.dispatchEvent === 'function') {
const detail = { key, value };
window.dispatchEvent(new CustomEvent('local-storage', { detail }));
}
}
type LocalStorageGetter = () => string;
type LocalStorageSetter = (value: string) => string;
export function useLocalStorage(key: string, defaultValue?: string): [
LocalStorageGetter,
LocalStorageSetter
] {
if (defaultValue != null && getItem(key) === null) {
setItem(key, defaultValue);
}
return [
() => getItem(key),
(value: string) => setItem(key, value)
];
}