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

useLiveQuery.ts

476 lines15.7 KB

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