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

useLiveQuery.ts

472 lines16.1 KB

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