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

useLiveQuery.ts

474 lines15.8 KB

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