-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathindex.ts
More file actions
44 lines (39 loc) · 1.25 KB
/
index.ts
File metadata and controls
44 lines (39 loc) · 1.25 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
import { createSignal, createEffect, onCleanup, Accessor } from "solid-js";
import type { Storage, StorageValue } from "unstorage";
export function createPersistedSignal<T extends StorageValue>(
storage: Storage,
key: string
): readonly [Accessor<T | undefined>, (v: T) => Promise<void>];
export function createPersistedSignal<T extends StorageValue>(
storage: Storage,
key: string,
init: T
): readonly [Accessor<T>, (v: T) => Promise<void>];
export function createPersistedSignal<T extends StorageValue>(
storage: Storage,
key: string,
init?: T
) {
const [value, _setValue] = createSignal<T | undefined>(init);
createEffect(() => {
storage.getItem<T>(key).then((v) => v && _setValue(() => v));
const unwatchPromise = storage.watch(async (e, k) => {
if (k === key) {
if (e === "update") {
const v = await storage.getItem<T>(key);
v && value() !== v && _setValue(() => v);
}
if (e === "remove") {
_setValue(() => init);
}
}
});
onCleanup(() => unwatchPromise.then((unwatch) => unwatch()));
});
const setValue = async (v: T) => {
if (v === value()) return;
_setValue(() => v);
await storage.setItem(key, v);
};
return [value, setValue] as const;
}