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