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

useLiveQuery.ts

478 lines15.9 KB

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