-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathuseDexieLiveQuery.ts
More file actions
119 lines (83 loc) · 2.61 KB
/
Copy pathuseDexieLiveQuery.ts
File metadata and controls
119 lines (83 loc) · 2.61 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
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
import { liveQuery, type Subscription } from "dexie";
import { shallowRef, getCurrentScope, onScopeDispose, watch, type ShallowRef, type WatchOptions } from "vue";
type Value<T, I> = I extends undefined ? T | undefined : T | I;
type UseDexieLiveQueryWithDepsOptions<I, Immediate> = {
onError?: (error: any) => void;
initialValue?: I;
} & WatchOptions<Immediate>;
type UseDexieLiveQueryOptions<I> = {
onError?: (error: any) => void;
initialValue?: I;
};
function tryOnScopeDispose(fn: () => void) {
if (getCurrentScope())
onScopeDispose(fn);
}
export function useDexieLiveQueryWithDeps<
T,
I = undefined,
Immediate extends Readonly<boolean> = true,
>(
deps: any,
querier: (...data: any) => T | Promise<T>,
options: UseDexieLiveQueryWithDepsOptions<I, Immediate> = {},
): ShallowRef<Value<T, I>> {
const { onError, initialValue, ...rest } = options;
const value = shallowRef<T | I | undefined>(initialValue);
let subscription: Subscription | undefined = undefined;
function start(...data: any) {
subscription?.unsubscribe();
const observable = liveQuery(() => querier(...data));
subscription = observable.subscribe({
next: result => {
value.value = result;
},
error: error => {
onError?.(error);
},
});
}
function cleanup() {
subscription?.unsubscribe();
// Set to undefined to avoid calling unsubscribe multiple times on a same subscription
subscription = undefined;
}
watch(deps, start, { immediate: true, ...rest });
tryOnScopeDispose(() => {
cleanup();
});
return value as ShallowRef<Value<T, I>>;
}
export function useDexieLiveQuery<
T,
I = undefined,
>(
querier: () => T | Promise<T>,
options: UseDexieLiveQueryOptions<I> = {},
): ShallowRef<Value<T, I>> {
const { onError, initialValue } = options;
const value = shallowRef<T | I | undefined>(initialValue);
let subscription: Subscription | undefined = undefined;
function start() {
subscription?.unsubscribe();
const observable = liveQuery(querier);
subscription = observable.subscribe({
next: result => {
value.value = result;
},
error: error => {
onError?.(error);
},
});
}
function cleanup() {
subscription?.unsubscribe();
// Set to undefined to avoid calling unsubscribe multiple times on a same subscription
subscription = undefined;
}
start();
tryOnScopeDispose(() => {
cleanup();
});
return value as ShallowRef<Value<T, I>>;
}