Skip to content
Source
Sign inSign up
TanStack/db
Open History to see the last commit

useLiveQuery.ts

473 lines16.1 KB

1import {
2 computed,
3 getCurrentInstance,
4 onUnmounted,
5 reactive,
6 ref,
7 shallowRef,
8 toValue,
9 watchEffect,
10} from 'vue'
11import {
12 BaseQueryBuilder,
13 createLiveQueryObserver,
14 getPublicCollection,
15 isCollection,
16 isSingleResultCollection,
17 resolveLiveQueryValue,
18} from '@tanstack/db'
19import type {
20 ChangeMessage,
21 Collection,
22 CollectionStatus,
23 Context,
24 GetResult,
25 InferResultType,
26 InitialQueryBuilder,
27 LiveQueryCollectionConfig,
28 LiveQueryObserver,
29 LiveQueryPersistedStatus,
30 NonSingleResult,
31 QueryBuilder,
32 SingleResult,
33} from '@tanstack/db'
34import type { ComputedRef, MaybeRefOrGetter } from 'vue'
35​
36const DEFAULT_GC_TIME_MS = 1
37​
38/** Copy a snapshot's ordered rows; a single-result query's `data` is one row. */
39function snapshotRows(data: unknown): Array<any> {
40 if (Array.isArray(data)) return [...data]
41 return data === undefined ? [] : [data]
43​
44/**
45 * Return type for useLiveQuery hook
46 * @property state - Reactive Map of query results (key → item)
47 * @property data - Reactive array of query results in order, or single result for findOne queries
48 * @property collection - The underlying query collection instance
49 * @property status - Current query status
50 * @property isLoading - True while initial query data is loading
51 * @property isReady - True when query has received first data and is ready
52 * @property isIdle - True when query hasn't started yet
53 * @property isError - True when query encountered an error
54 * @property isCleanedUp - True when query has been cleaned up
55 */
56export interface UseLiveQueryReturn<TContext extends Context> {
57 state: ComputedRef<Map<string | number, GetResult<TContext>>>
58 data: ComputedRef<InferResultType<TContext>>
59 collection: ComputedRef<Collection<GetResult<TContext>, string | number, {}>>
60 status: ComputedRef<CollectionStatus>
61 isLoading: ComputedRef<boolean>
62 isReady: ComputedRef<boolean>
63 persistedStatus: ComputedRef<LiveQueryPersistedStatus>
64 isPersistedReady: ComputedRef<boolean>
65 persistedError: ComputedRef<unknown | undefined>
66 isIdle: ComputedRef<boolean>
67 isError: ComputedRef<boolean>
68 isCleanedUp: ComputedRef<boolean>
70​
71type InferConditionalResultType<TContext extends Context> =
72 TContext extends SingleResult
73 ? InferResultType<TContext> | []
74 : InferResultType<TContext>
75​
76export type ConditionalUseLiveQueryReturn<TContext extends Context> = Omit<
77 UseLiveQueryReturn<TContext>,
78 `data` | `collection` | `status`
79> & {
80 data: ComputedRef<InferConditionalResultType<TContext>>
81 collection: ComputedRef<Collection<
82 GetResult<TContext>,
83 string | number,
84 {}
85 > | null>
86 status: ComputedRef<CollectionStatus | `disabled`>
88​
89export interface UseLiveQueryReturnWithCollection<
90 T extends object,
91 TKey extends string | number,
92 TUtils extends Record<string, any>,
93> {
94 state: ComputedRef<Map<TKey, T>>
95 data: ComputedRef<Array<T>>
96 collection: ComputedRef<Collection<T, TKey, TUtils>>
97 status: ComputedRef<CollectionStatus>
98 isLoading: ComputedRef<boolean>
99 isReady: ComputedRef<boolean>
100 persistedStatus: ComputedRef<LiveQueryPersistedStatus>
101 isPersistedReady: ComputedRef<boolean>
102 persistedError: ComputedRef<unknown | undefined>
103 isIdle: ComputedRef<boolean>
104 isError: ComputedRef<boolean>
105 isCleanedUp: ComputedRef<boolean>
107​
108export interface UseLiveQueryReturnWithSingleResultCollection<
109 T extends object,
110 TKey extends string | number,
111 TUtils extends Record<string, any>,
112> {
113 state: ComputedRef<Map<TKey, T>>
114 data: ComputedRef<T | undefined>
115 collection: ComputedRef<Collection<T, TKey, TUtils> & SingleResult>
116 status: ComputedRef<CollectionStatus>
117 isLoading: ComputedRef<boolean>
118 isReady: ComputedRef<boolean>
119 persistedStatus: ComputedRef<LiveQueryPersistedStatus>
120 isPersistedReady: ComputedRef<boolean>
121 persistedError: ComputedRef<unknown | undefined>
122 isIdle: ComputedRef<boolean>
123 isError: ComputedRef<boolean>
124 isCleanedUp: ComputedRef<boolean>
126​
127/**
128 * Create a live query using a query function
129 * @param queryFn - Query function that defines what data to fetch
130 * @param deps - Array of reactive dependencies that trigger query re-execution when changed
131 * @returns Reactive object with query data, state, and status information
132 * @example
133 * // Basic query with object syntax
134 * const { data, isLoading } = useLiveQuery((q) =>
135 * q.from({ todos: todosCollection })
136 * .where(({ todos }) => eq(todos.completed, false))
137 * .select(({ todos }) => ({ id: todos.id, text: todos.text }))
138 * )
139 *
140 * @example
141 * // With reactive dependencies
142 * const minPriority = ref(5)
143 * const { data, state } = useLiveQuery(
144 * (q) => q.from({ todos: todosCollection })
145 * .where(({ todos }) => gt(todos.priority, minPriority.value)),
146 * [minPriority] // Re-run when minPriority changes
147 * )
148 *
149 * @example
150 * // Join pattern
151 * const { data } = useLiveQuery((q) =>
152 * q.from({ issues: issueCollection })
153 * .join({ persons: personCollection }, ({ issues, persons }) =>
154 * eq(issues.userId, persons.id)
155 * )
156 * .select(({ issues, persons }) => ({
157 * id: issues.id,
158 * title: issues.title,
159 * userName: persons.name
160 * }))
161 * )
162 *
163 * @example
164 * // Handle loading and error states in template
165 * const { data, isLoading, isError, status } = useLiveQuery((q) =>
166 * q.from({ todos: todoCollection })
167 * )
168 *
169 * // In template:
170 * // <div v-if="isLoading">Loading...</div>
171 * // <div v-else-if="isError">Error: {{ status }}</div>
172 * // <ul v-else>
173 * // <li v-for="todo in data" :key="todo.id">{{ todo.text }}</li>
174 * // </ul>
175 */
176// Overload 1: Accept query function that always returns QueryBuilder
177export function useLiveQuery<TContext extends Context>(
178 queryFn: (q: InitialQueryBuilder) => QueryBuilder<TContext>,
179 deps?: Array<MaybeRefOrGetter<unknown>>,
180): UseLiveQueryReturn<TContext>
181​
182// Overload 1b: Accept query function that can return undefined/null
183export function useLiveQuery<TContext extends Context>(
184 queryFn: (
185 q: InitialQueryBuilder,
186 ) => QueryBuilder<TContext> | undefined | null,
187 deps?: Array<MaybeRefOrGetter<unknown>>,
188): ConditionalUseLiveQueryReturn<TContext>
189​
190/**
191 * Create a live query using configuration object
192 * @param config - Configuration object with query and options
193 * @param deps - Array of reactive dependencies that trigger query re-execution when changed
194 * @returns Reactive object with query data, state, and status information
195 * @example
196 * // Basic config object usage
197 * const { data, status } = useLiveQuery({
198 * query: (q) => q.from({ todos: todosCollection }),
199 * gcTime: 60000
200 * })
201 *
202 * @example
203 * // With reactive dependencies
204 * const filter = ref('active')
205 * const { data, isReady } = useLiveQuery({
206 * query: (q) => q.from({ todos: todosCollection })
207 * .where(({ todos }) => eq(todos.status, filter.value))
208 * }, [filter])
209 *
210 * @example
211 * // Handle all states uniformly
212 * const { data, isLoading, isReady, isError } = useLiveQuery({
213 * query: (q) => q.from({ items: itemCollection })
214 * })
215 *
216 * // In template:
217 * // <div v-if="isLoading">Loading...</div>
218 * // <div v-else-if="isError">Something went wrong</div>
219 * // <div v-else-if="!isReady">Preparing...</div>
220 * // <div v-else>{{ data.length }} items loaded</div>
221 */
222// Overload 2: Accept config object
223export function useLiveQuery<TContext extends Context>(
224 config: LiveQueryCollectionConfig<TContext>,
225 deps?: Array<MaybeRefOrGetter<unknown>>,
226): UseLiveQueryReturn<TContext>
227​
228/**
229 * Subscribe to an existing query collection (can be reactive)
230 * @param liveQueryCollection - Pre-created query collection to subscribe to (can be a ref)
231 * @returns Reactive object with query data, state, and status information
232 * @example
233 * // Using pre-created query collection
234 * const myLiveQuery = createLiveQueryCollection((q) =>
235 * q.from({ todos: todosCollection }).where(({ todos }) => eq(todos.active, true))
236 * )
237 * const { data, collection } = useLiveQuery(myLiveQuery)
238 *
239 * @example
240 * // Reactive query collection reference
241 * const selectedQuery = ref(todosQuery)
242 * const { data, collection } = useLiveQuery(selectedQuery)
243 *
244 * // Switch queries reactively
245 * selectedQuery.value = archiveQuery
246 *
247 * @example
248 * // Access query collection methods directly
249 * const { data, collection, isReady } = useLiveQuery(existingQuery)
250 *
251 * // Use underlying collection for mutations
252 * const handleToggle = (id) => {
253 * collection.value.update(id, draft => { draft.completed = !draft.completed })
254 * }
255 *
256 * @example
257 * // Handle states consistently
258 * const { data, isLoading, isError } = useLiveQuery(sharedQuery)
259 *
260 * // In template:
261 * // <div v-if="isLoading">Loading...</div>
262 * // <div v-else-if="isError">Error loading data</div>
263 * // <div v-else>
264 * // <Item v-for="item in data" :key="item.id" v-bind="item" />
265 * // </div>
266 */
267// Overload 3: Accept pre-created live query collection (can be reactive) - non-single result
268export function useLiveQuery<
269 TResult extends object,
270 TKey extends string | number,
271 TUtils extends Record<string, any>,
272>(
273 liveQueryCollection: MaybeRefOrGetter<
274 Collection<TResult, TKey, TUtils> & NonSingleResult
275 >,
276): UseLiveQueryReturnWithCollection<TResult, TKey, TUtils>
277​
278// Overload 4: Accept pre-created live query collection with singleResult: true
279export function useLiveQuery<
280 TResult extends object,
281 TKey extends string | number,
282 TUtils extends Record<string, any>,
283>(
284 liveQueryCollection: MaybeRefOrGetter<
285 Collection<TResult, TKey, TUtils> & SingleResult
286 >,
287): UseLiveQueryReturnWithSingleResultCollection<TResult, TKey, TUtils>
288​
289// Implementation
290export function useLiveQuery(
291 configOrQueryOrCollection: any,
292 deps: Array<MaybeRefOrGetter<unknown>> = [],
293): UseLiveQueryReturn<any> | UseLiveQueryReturnWithCollection<any, any, any> {
294 const collection = computed(() => {
295 // First check if the original parameter might be a ref/getter
296 // by seeing if toValue returns something different than the original
297 // NOTE: Don't call toValue on functions - toValue treats functions as getters and calls them!
298 let unwrappedParam = configOrQueryOrCollection
299 if (typeof configOrQueryOrCollection !== `function`) {
300 try {
301 const potentiallyUnwrapped = toValue(configOrQueryOrCollection)
302 if (potentiallyUnwrapped !== configOrQueryOrCollection) {
303 unwrappedParam = potentiallyUnwrapped
304 }
305 } catch {
306 // If toValue fails, use original parameter
307 unwrappedParam = configOrQueryOrCollection
308 }
309 }
310​
311 // Check if it's already a collection
312 const inputIsCollection = isCollection(unwrappedParam)
313​
314 if (inputIsCollection) {
315 // Warn when passing a collection directly with on-demand sync mode
316 // In on-demand mode, data is only loaded when queries with predicates request it
317 // Passing the collection directly doesn't provide any predicates, so no data loads
318 const syncMode = (unwrappedParam as { config?: { syncMode?: string } })
319 .config?.syncMode
320 if (syncMode === `on-demand`) {
321 console.warn(
322 `[useLiveQuery] Warning: Passing a collection with syncMode "on-demand" directly to useLiveQuery ` +
323 `will not load any data. In on-demand mode, data is only loaded when queries with predicates request it.\n\n` +
324 `Instead, use a query builder function:\n` +
325 ` const { data } = useLiveQuery((q) => q.from({ c: myCollection }).select(({ c }) => c))\n\n` +
326 `Or switch to syncMode "eager" if you want all data to sync automatically.`,
327 )
328 }
329 // It's already a collection, ensure sync is started for Vue hooks
330 // Only start sync if the collection is in idle state
331 if (unwrappedParam.status === `idle`) {
332 unwrappedParam.startSyncImmediate()
333 }
334 return unwrappedParam
335 }
336​
337 // Reference deps to make computed reactive to them
338 deps.forEach((dep) => toValue(dep))
339​
340 // Ensure we always start sync for Vue hooks
341 if (typeof unwrappedParam === `function`) {
342 // A query function returning null or undefined disables the query.
343 return resolveLiveQueryValue(
344 unwrappedParam(new BaseQueryBuilder() as InitialQueryBuilder),
345 { gcTime: DEFAULT_GC_TIME_MS },
346 )
347 } else {
348 return resolveLiveQueryValue(unwrappedParam, {
349 gcTime: DEFAULT_GC_TIME_MS,
350 })
351 }
352 })
353​
354 // Reactive state that gets updated granularly through change events
355 const state = reactive(new Map<string | number, any>())
356​
357 // Reactive data array that maintains sorted order
358 const internalData = ref<Array<any>>([])
359​
360 // Computed wrapper for the data to match expected return type
361 // Returns single item for singleResult collections, array otherwise
362 const data = computed(() => {
363 const currentCollection = collection.value
364 if (!currentCollection) {
365 return internalData.value
366 }
367 return isSingleResultCollection(currentCollection)
368 ? internalData.value[0]
369 : internalData.value
370 })
371​
372 // Track collection status reactively
373 const status = ref(
374 collection.value ? collection.value.status : (`disabled` as const),
375 )
376 const persistedStatus = ref<LiveQueryPersistedStatus>(`unavailable`)
377 const persistedError = shallowRef<unknown>(undefined)
378​
379 // The shared observer owns subscription, the ready-race, and status; Vue
380 // materializes into its own reactive map (granular) + ordered array.
381 let currentObserver: LiveQueryObserver<any, any> | null = null
382​
383 const syncFromObserver = (observer: LiveQueryObserver<any, any>) => {
384 const snapshot = observer.getSnapshot()
385 status.value = snapshot.status as CollectionStatus
386 persistedStatus.value = snapshot.persistedStatus
387 persistedError.value = snapshot.persistedError
388 internalData.value = snapshotRows(snapshot.data)
389 }
390​
391 // Watch for collection changes and subscribe to updates
392 watchEffect((onInvalidate) => {
393 const currentCollection = collection.value
394​
395 // Tear down any previous observer.
396 currentObserver?.dispose()
397 currentObserver = null
398​
399 // Handle null collection (disabled query)
400 if (!currentCollection) {
401 status.value = `disabled` as const
402 persistedStatus.value = `unavailable`
403 persistedError.value = undefined
404 state.clear()
405 internalData.value = []
406 return
407 }
408​
409 const observer = createLiveQueryObserver(currentCollection)
410 currentObserver = observer
411​
412 // Initial rows arrive as the observer's first delta (includeInitialState);
413 // apply them and every subsequent delta granularly to the reactive map.
414 state.clear()
415​
416 const unsubscribe = observer.subscribe(
417 (changes: Array<ChangeMessage<any>> | undefined) => {
418 if (changes) {
419 for (const change of changes) {
420 switch (change.type) {
421 case `insert`:
422 case `update`:
423 state.set(change.key, change.value)
424 break
425 case `delete`:
426 state.delete(change.key)
427 break
428 }
429 }
430 } else {
431 // Cleanup and other status-only publications carry no row deltas.
432 // Rebuild the keyed view so it cannot diverge from ordered data.
433 state.clear()
434 for (const [key, value] of observer.getSnapshot().state ?? []) {
435 state.set(key, value)
436 }
437 }
438 syncFromObserver(observer)
439 },
440 )
441 syncFromObserver(observer)
442​
443 // Cleanup when effect is invalidated
444 onInvalidate(() => {
445 unsubscribe()
446 observer.dispose()
447 currentObserver = null
448 })
449 })
450​
451 // Cleanup on unmount (only if we're in a component context)
452 const instance = getCurrentInstance()
453 if (instance) {
454 onUnmounted(() => currentObserver?.dispose())
455 }
456​
457 return {
458 state: computed(() => state),
459 data,
460 collection: computed(() => getPublicCollection(collection.value)),
461 status: computed(() => status.value),
462 isLoading: computed(() => status.value === `loading`),
463 isReady: computed(
464 () => status.value === `ready` || status.value === `disabled`,
465 ),
466 persistedStatus: computed(() => persistedStatus.value),
467 isPersistedReady: computed(() => persistedStatus.value === `ready`),
468 persistedError: computed(() => persistedError.value),
469 isIdle: computed(() => status.value === `idle`),
470 isError: computed(() => status.value === `error`),
471 isCleanedUp: computed(() => status.value === `cleaned-up`),
472 }