-
Notifications
You must be signed in to change notification settings - Fork 52
Expand file tree
/
Copy pathcreateStorage.ts
More file actions
57 lines (51 loc) · 1.34 KB
/
createStorage.ts
File metadata and controls
57 lines (51 loc) · 1.34 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
49
50
51
52
53
54
55
56
57
import { createObserver } from "./createObserver.ts";
const createMemoryStorage = (): Storage => {
const store = new Map<string, string>();
return {
get length() {
return store.size;
},
clear() {
store.clear();
},
getItem(key: string) {
return store.has(key) ? store.get(key)! : null;
},
key(index: number) {
return Array.from(store.keys())[index] ?? null;
},
removeItem(key: string) {
store.delete(key);
},
setItem(key: string, value: string) {
store.set(key, value);
},
} as Storage;
};
export const createStorage = <T>(
key: string,
storage: Storage = typeof window !== "undefined" ? window.localStorage : createMemoryStorage(),
) => {
let data: T | null = JSON.parse(storage.getItem(key) ?? "null");
const { subscribe, notify } = createObserver();
const get = () => data;
const set = (value: T) => {
try {
data = value;
storage.setItem(key, JSON.stringify(data));
notify();
} catch (error) {
console.error(`Error setting storage item for key "${key}":`, error);
}
};
const reset = () => {
try {
data = null;
storage.removeItem(key);
notify();
} catch (error) {
console.error(`Error removing storage item for key "${key}":`, error);
}
};
return { get, set, reset, subscribe };
};