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