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