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

useLiveQuery.ts

485 lines16.4 KB

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