-
Notifications
You must be signed in to change notification settings - Fork 56
Expand file tree
/
Copy pathcreateStorage.ts
More file actions
49 lines (43 loc) · 1.33 KB
/
createStorage.ts
File metadata and controls
49 lines (43 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
38
39
40
41
42
43
44
45
46
47
48
49
import { createObserver } from "./createObserver.ts";
export const createStorage = <T>(key: string, storage = window.localStorage) => {
let data: T | null;
try {
const storedValue = storage.getItem(key);
if (storedValue === null) {
console.log(`[createStorage] No stored value for ${key}, initializing as null`);
data = null;
} else {
data = JSON.parse(storedValue);
console.log(`[createStorage] Successfully loaded ${key}:`, data);
}
} catch (error) {
console.error(`[createStorage] Error parsing data for ${key}:`, error);
data = null;
}
const { subscribe, notify } = createObserver();
const get = () => {
return data;
};
const set = (value: T) => {
try {
data = value;
const serialized = JSON.stringify(data);
storage.setItem(key, serialized);
console.log(`[createStorage] Successfully stored ${key}`);
notify();
} catch (error) {
console.error(`Error setting storage item for key "${key}":`, error);
}
};
const reset = () => {
try {
data = null;
storage.removeItem(key);
console.log(`[createStorage] Successfully removed ${key} from storage`);
notify();
} catch (error) {
console.error(`Error removing storage item for key "${key}":`, error);
}
};
return { get, set, reset, subscribe };
};