-
-
Notifications
You must be signed in to change notification settings - Fork 1.9k
/
create-storage.ts
188 lines (158 loc) · 5.28 KB
/
create-storage.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
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
/* eslint-disable no-console */
import { useCallback, useEffect, useState } from 'react';
import { useWindowEvent } from '../use-window-event/use-window-event';
export type StorageType = 'localStorage' | 'sessionStorage';
export interface StorageProperties<T> {
/** Storage key */
key: string;
/** Default value that will be set if value is not found in storage */
defaultValue?: T;
/** If set to true, value will be updated in useEffect after mount. Default value is true. */
getInitialValueInEffect?: boolean;
/** Function to serialize value into string to be save in storage */
serialize?: (value: T) => string;
/** Function to deserialize string value from storage to value */
deserialize?: (value: string | undefined) => T;
}
function serializeJSON<T>(value: T, hookName: string = 'use-local-storage') {
try {
return JSON.stringify(value);
} catch (error) {
throw new Error(`@mantine/hooks ${hookName}: Failed to serialize the value`);
}
}
function deserializeJSON(value: string | undefined) {
try {
return value && JSON.parse(value);
} catch {
return value;
}
}
function createStorageHandler(type: StorageType) {
const getItem = (key: string) => {
try {
return window[type].getItem(key);
} catch (error) {
console.warn('use-local-storage: Failed to get value from storage, localStorage is blocked');
return null;
}
};
const setItem = (key: string, value: string) => {
try {
window[type].setItem(key, value);
} catch (error) {
console.warn('use-local-storage: Failed to set value to storage, localStorage is blocked');
}
};
const removeItem = (key: string) => {
try {
window[type].removeItem(key);
} catch (error) {
console.warn(
'use-local-storage: Failed to remove value from storage, localStorage is blocked'
);
}
};
return { getItem, setItem, removeItem };
}
export function createStorage<T>(type: StorageType, hookName: string) {
const eventName = type === 'localStorage' ? 'mantine-local-storage' : 'mantine-session-storage';
const { getItem, setItem, removeItem } = createStorageHandler(type);
return function useStorage({
key,
defaultValue,
getInitialValueInEffect = true,
deserialize = deserializeJSON,
serialize = (value: T) => serializeJSON(value, hookName),
}: StorageProperties<T>) {
const readStorageValue = useCallback(
(skipStorage?: boolean): T => {
let storageBlockedOrSkipped;
try {
storageBlockedOrSkipped =
typeof window === 'undefined' ||
!(type in window) ||
window[type] === null ||
!!skipStorage;
} catch (_e) {
storageBlockedOrSkipped = true;
}
if (storageBlockedOrSkipped) {
return defaultValue as T;
}
const storageValue = getItem(key);
return storageValue !== null ? deserialize(storageValue) : (defaultValue as T);
},
[key, defaultValue]
);
const [value, setValue] = useState<T>(readStorageValue(getInitialValueInEffect));
const setStorageValue = useCallback(
(val: T | ((prevState: T) => T)) => {
if (val instanceof Function) {
setValue((current) => {
const result = val(current);
setItem(key, serialize(result));
window.dispatchEvent(
new CustomEvent(eventName, { detail: { key, value: val(current) } })
);
return result;
});
} else {
setItem(key, serialize(val));
window.dispatchEvent(new CustomEvent(eventName, { detail: { key, value: val } }));
setValue(val);
}
},
[key]
);
const removeStorageValue = useCallback(() => {
removeItem(key);
window.dispatchEvent(new CustomEvent(eventName, { detail: { key, value: defaultValue } }));
}, []);
useWindowEvent('storage', (event) => {
if (event.storageArea === window[type] && event.key === key) {
setValue(deserialize(event.newValue ?? undefined));
}
});
useWindowEvent(eventName, (event) => {
if (event.detail.key === key) {
setValue(event.detail.value);
}
});
useEffect(() => {
if (defaultValue !== undefined && value === undefined) {
setStorageValue(defaultValue);
}
}, [defaultValue, value, setStorageValue]);
useEffect(() => {
const val = readStorageValue();
val !== undefined && setStorageValue(val);
}, []);
return [value === undefined ? defaultValue : value, setStorageValue, removeStorageValue] as [
T,
(val: T | ((prevState: T) => T)) => void,
() => void,
];
};
}
export function readValue(type: StorageType) {
const { getItem } = createStorageHandler(type);
return function read<T>({
key,
defaultValue,
deserialize = deserializeJSON,
}: StorageProperties<T>) {
let storageBlockedOrSkipped;
try {
storageBlockedOrSkipped =
typeof window === 'undefined' || !(type in window) || window[type] === null;
} catch (_e) {
storageBlockedOrSkipped = true;
}
if (storageBlockedOrSkipped) {
return defaultValue as T;
}
const storageValue = getItem(key);
return storageValue !== null ? deserialize(storageValue) : (defaultValue as T);
};
}