Open History to see the last commit
1import { useRef, useSyncExternalStore } from 'react'
2import {
3 BaseQueryBuilder,
4 createLiveQueryCollection,
5 getLiveQueryStatusFlags,
6 isCollection,
7 isSingleResultCollection,
8} from '@tanstack/db'
9import type {
10 Collection,
11 CollectionStatus,
12 Context,
13 GetResult,
14 InferResultType,
15 InitialQueryBuilder,
16 LiveQueryCollectionConfig,
17 NonSingleResult,
18 QueryBuilder,
19 SingleResult,
20} from '@tanstack/db'
21
22const DEFAULT_GC_TIME_MS = 1 // Live queries created by useLiveQuery are cleaned up immediately (0 disables GC)
23
24export type UseLiveQueryStatus = CollectionStatus | `disabled`
25
26/**
27 * Create a live query using a query function
28 * @param queryFn - Query function that defines what data to fetch
29 * @param deps - Array of dependencies that trigger query re-execution when changed
30 * @returns Object with reactive data, state, and status information
31 * @example
32 * // Basic query with object syntax
33 * const { data, isLoading } = useLiveQuery((q) =>
34 * q.from({ todos: todosCollection })
35 * .where(({ todos }) => eq(todos.completed, false))
36 * .select(({ todos }) => ({ id: todos.id, text: todos.text }))
37 * )
38 *
39 * @example
40 * // Single result query
41 * const { data } = useLiveQuery(
42 * (q) => q.from({ todos: todosCollection })
43 * .where(({ todos }) => eq(todos.id, 1))
44 * .findOne()
45 * )
46 *
47 * @example
48 * // With dependencies that trigger re-execution
49 * const { data, state } = useLiveQuery(
50 * (q) => q.from({ todos: todosCollection })
51 * .where(({ todos }) => gt(todos.priority, minPriority)),
52 * [minPriority] // Re-run when minPriority changes
53 * )
54 *
55 * @example
56 * // Join pattern
57 * const { data } = useLiveQuery((q) =>
58 * q.from({ issues: issueCollection })
59 * .join({ persons: personCollection }, ({ issues, persons }) =>
60 * eq(issues.userId, persons.id)
61 * )
62 * .select(({ issues, persons }) => ({
63 * id: issues.id,
64 * title: issues.title,
65 * userName: persons.name
66 * }))
67 * )
68 *
69 * @example
70 * // Handle loading and error states
71 * const { data, isLoading, isError, status } = useLiveQuery((q) =>
72 * q.from({ todos: todoCollection })
73 * )
74 *
75 * if (isLoading) return <div>Loading...</div>
76 * if (isError) return <div>Error: {status}</div>
77 *
78 * return (
79 * <ul>
80 * {data.map(todo => <li key={todo.id}>{todo.text}</li>)}
81 * </ul>
82 * )
83 */
84// Overload 1: Accept query function that always returns QueryBuilder
85export function useLiveQuery<TContext extends Context>(
86 queryFn: (q: InitialQueryBuilder) => QueryBuilder<TContext>,
87 deps?: Array<unknown>,
88): {
89 state: Map<string | number, GetResult<TContext>>
90 data: InferResultType<TContext>
91 collection: Collection<GetResult<TContext>, string | number, {}>
92 status: CollectionStatus // Can't be disabled if always returns QueryBuilder
93 isLoading: boolean
94 isReady: boolean
95 isIdle: boolean
96 isError: boolean
97 isCleanedUp: boolean
98 isEnabled: true // Always true if always returns QueryBuilder
99}
100
101// Overload 2: Accept query function that can return undefined/null
102export function useLiveQuery<TContext extends Context>(
103 queryFn: (
104 q: InitialQueryBuilder,
105 ) => QueryBuilder<TContext> | undefined | null,
106 deps?: Array<unknown>,
107): {
108 state: Map<string | number, GetResult<TContext>> | undefined
109 data: InferResultType<TContext> | undefined
110 collection: Collection<GetResult<TContext>, string | number, {}> | undefined
111 status: UseLiveQueryStatus
112 isLoading: boolean
113 isReady: boolean
114 isIdle: boolean
115 isError: boolean
116 isCleanedUp: boolean
117 isEnabled: boolean
118}
119
120// Overload 3: Accept query function that can return LiveQueryCollectionConfig
121export function useLiveQuery<TContext extends Context>(
122 queryFn: (
123 q: InitialQueryBuilder,
124 ) => LiveQueryCollectionConfig<TContext> | undefined | null,
125 deps?: Array<unknown>,
126): {
127 state: Map<string | number, GetResult<TContext>> | undefined
128 data: InferResultType<TContext> | undefined
129 collection: Collection<GetResult<TContext>, string | number, {}> | undefined
130 status: UseLiveQueryStatus
131 isLoading: boolean
132 isReady: boolean
133 isIdle: boolean
134 isError: boolean
135 isCleanedUp: boolean
136 isEnabled: boolean
137}
138
139// Overload 4: Accept query function that can return Collection
140export function useLiveQuery<
141 TResult extends object,
142 TKey extends string | number,
143 TUtils extends Record<string, any>,
144>(
145 queryFn: (
146 q: InitialQueryBuilder,
147 ) => Collection<TResult, TKey, TUtils> | undefined | null,
148 deps?: Array<unknown>,
149): {
150 state: Map<TKey, TResult> | undefined
151 data: Array<TResult> | undefined
152 collection: Collection<TResult, TKey, TUtils> | undefined
153 status: UseLiveQueryStatus
154 isLoading: boolean
155 isReady: boolean
156 isIdle: boolean
157 isError: boolean
158 isCleanedUp: boolean
159 isEnabled: boolean
160}
161
162// Overload 5: Accept query function that can return all types
163export function useLiveQuery<
164 TContext extends Context,
165 TResult extends object,
166 TKey extends string | number,
167 TUtils extends Record<string, any>,
168>(
169 queryFn: (
170 q: InitialQueryBuilder,
171 ) =>
172 | QueryBuilder<TContext>
173 | LiveQueryCollectionConfig<TContext>
174 | Collection<TResult, TKey, TUtils>
175 | undefined
176 | null,
177 deps?: Array<unknown>,
178): {
179 state:
180 | Map<string | number, GetResult<TContext>>
181 | Map<TKey, TResult>
182 | undefined
183 data: InferResultType<TContext> | Array<TResult> | undefined
184 collection:
185 | Collection<GetResult<TContext>, string | number, {}>
186 | Collection<TResult, TKey, TUtils>
187 | undefined
188 status: UseLiveQueryStatus
189 isLoading: boolean
190 isReady: boolean
191 isIdle: boolean
192 isError: boolean
193 isCleanedUp: boolean
194 isEnabled: boolean
195}
196
197/**
198 * Create a live query using configuration object
199 * @param config - Configuration object with query and options
200 * @param deps - Array of dependencies that trigger query re-execution when changed
201 * @returns Object with reactive data, state, and status information
202 * @example
203 * // Basic config object usage
204 * const { data, status } = useLiveQuery({
205 * query: (q) => q.from({ todos: todosCollection }),
206 * gcTime: 60000
207 * })
208 *
209 * @example
210 * // With query builder and options
211 * const queryBuilder = new Query()
212 * .from({ persons: collection })
213 * .where(({ persons }) => gt(persons.age, 30))
214 * .select(({ persons }) => ({ id: persons.id, name: persons.name }))
215 *
216 * const { data, isReady } = useLiveQuery({ query: queryBuilder })
217 *
218 * @example
219 * // Handle all states uniformly
220 * const { data, isLoading, isReady, isError } = useLiveQuery({
221 * query: (q) => q.from({ items: itemCollection })
222 * })
223 *
224 * if (isLoading) return <div>Loading...</div>
225 * if (isError) return <div>Something went wrong</div>
226 * if (!isReady) return <div>Preparing...</div>
227 *
228 * return <div>{data.length} items loaded</div>
229 */
230// Overload 6: Accept config object
231export function useLiveQuery<TContext extends Context>(
232 config: LiveQueryCollectionConfig<TContext>,
233 deps?: Array<unknown>,
234): {
235 state: Map<string | number, GetResult<TContext>>
236 data: InferResultType<TContext>
237 collection: Collection<GetResult<TContext>, string | number, {}>
238 status: CollectionStatus // Can't be disabled for config objects
239 isLoading: boolean
240 isReady: boolean
241 isIdle: boolean
242 isError: boolean
243 isCleanedUp: boolean
244 isEnabled: true // Always true for config objects
245}
246
247/**
248 * Subscribe to an existing live query collection
249 * @param liveQueryCollection - Pre-created live query collection to subscribe to
250 * @returns Object with reactive data, state, and status information
251 * @example
252 * // Using pre-created live query collection
253 * const myLiveQuery = createLiveQueryCollection((q) =>
254 * q.from({ todos: todosCollection }).where(({ todos }) => eq(todos.active, true))
255 * )
256 * const { data, collection } = useLiveQuery(myLiveQuery)
257 *
258 * @example
259 * // Access collection methods directly
260 * const { data, collection, isReady } = useLiveQuery(existingCollection)
261 *
262 * // Use collection for mutations
263 * const handleToggle = (id) => {
264 * collection.update(id, draft => { draft.completed = !draft.completed })
265 * }
266 *
267 * @example
268 * // Handle states consistently
269 * const { data, isLoading, isError } = useLiveQuery(sharedCollection)
270 *
271 * if (isLoading) return <div>Loading...</div>
272 * if (isError) return <div>Error loading data</div>
273 *
274 * return <div>{data.map(item => <Item key={item.id} {...item} />)}</div>
275 */
276// Overload 7: Accept pre-created live query collection
277export function useLiveQuery<
278 TResult extends object,
279 TKey extends string | number,
280 TUtils extends Record<string, any>,
281>(
282 liveQueryCollection: Collection<TResult, TKey, TUtils> & NonSingleResult,
283): {
284 state: Map<TKey, TResult>
285 data: Array<TResult>
286 collection: Collection<TResult, TKey, TUtils>
287 status: CollectionStatus // Can't be disabled for pre-created live query collections
288 isLoading: boolean
289 isReady: boolean
290 isIdle: boolean
291 isError: boolean
292 isCleanedUp: boolean
293 isEnabled: true // Always true for pre-created live query collections
294}
295
296// Overload 8: Accept pre-created live query collection with singleResult: true
297export function useLiveQuery<
298 TResult extends object,
299 TKey extends string | number,
300 TUtils extends Record<string, any>,
301>(
302 liveQueryCollection: Collection<TResult, TKey, TUtils> & SingleResult,
303): {
304 state: Map<TKey, TResult>
305 data: TResult | undefined
306 collection: Collection<TResult, TKey, TUtils> & SingleResult
307 status: CollectionStatus // Can't be disabled for pre-created live query collections
308 isLoading: boolean
309 isReady: boolean
310 isIdle: boolean
311 isError: boolean
312 isCleanedUp: boolean
313 isEnabled: true // Always true for pre-created live query collections
314}
315
316// Implementation - use function overloads to infer the actual collection type
317export function useLiveQuery(
318 configOrQueryOrCollection: any,
319 deps: Array<unknown> = [],
320) {
321 // Check if it's already a collection
322 const inputIsCollection = isCollection(configOrQueryOrCollection)
323
324 // Use refs to cache collection and track dependencies
325 const collectionRef = useRef<Collection<object, string | number, {}> | null>(
326 null,
327 )
328 const depsRef = useRef<Array<unknown> | null>(null)
329 const configRef = useRef<unknown>(null)
330
331 // Use refs to track version and memoized snapshot
332 const versionRef = useRef(0)
333 const snapshotRef = useRef<{
334 collection: Collection<object, string | number, {}> | null
335 version: number
336 } | null>(null)
337
338 // Check if we need to create/recreate the collection
339 const needsNewCollection =
340 !collectionRef.current ||
341 (inputIsCollection && configRef.current !== configOrQueryOrCollection) ||
342 (!inputIsCollection &&
343 (depsRef.current === null ||
344 depsRef.current.length !== deps.length ||
345 depsRef.current.some((dep, i) => dep !== deps[i])))
346
347 if (needsNewCollection) {
348 if (inputIsCollection) {
349 // Warn when passing a collection directly with on-demand sync mode
350 // In on-demand mode, data is only loaded when queries with predicates request it
351 // Passing the collection directly doesn't provide any predicates, so no data loads
352 const syncMode = (
353 configOrQueryOrCollection as { config?: { syncMode?: string } }
354 ).config?.syncMode
355 if (syncMode === `on-demand`) {
356 console.warn(
357 `[useLiveQuery] Warning: Passing a collection with syncMode "on-demand" directly to useLiveQuery ` +
358 `will not load any data. In on-demand mode, data is only loaded when queries with predicates request it.\n\n` +
359 `Instead, use a query builder function:\n` +
360 ` const { data } = useLiveQuery((q) => q.from({ c: myCollection }).select(({ c }) => c))\n\n` +
361 `Or switch to syncMode "eager" if you want all data to sync automatically.`,
362 )
363 }
364 // It's already a collection, ensure sync is started for React hooks
365 configOrQueryOrCollection.startSyncImmediate()
366 collectionRef.current = configOrQueryOrCollection
367 configRef.current = configOrQueryOrCollection
368 } else {
369 // Handle different callback return types
370 if (typeof configOrQueryOrCollection === `function`) {
371 // Call the function with a query builder to see what it returns
372 const queryBuilder = new BaseQueryBuilder() as InitialQueryBuilder
373 const result = configOrQueryOrCollection(queryBuilder)
374
375 if (result === undefined || result === null) {
376 // Callback returned undefined/null - disabled query
377 collectionRef.current = null
378 } else if (isCollection(result)) {
379 // Callback returned a Collection instance - use it directly
380 result.startSyncImmediate()
381 collectionRef.current = result
382 } else if (result instanceof BaseQueryBuilder) {
383 // Callback returned QueryBuilder - create live query collection using the original callback
384 // (not the result, since the result might be from a different query builder instance)
385 collectionRef.current = createLiveQueryCollection({
386 query: configOrQueryOrCollection,
387 startSync: true,
388 gcTime: DEFAULT_GC_TIME_MS,
389 })
390 } else if (result && typeof result === `object`) {
391 // Assume it's a LiveQueryCollectionConfig
392 collectionRef.current = createLiveQueryCollection({
393 startSync: true,
394 gcTime: DEFAULT_GC_TIME_MS,
395 ...result,
396 })
397 } else {
398 // Unexpected return type
399 throw new Error(
400 `useLiveQuery callback must return a QueryBuilder, LiveQueryCollectionConfig, Collection, undefined, or null. Got: ${typeof result}`,
401 )
402 }
403 depsRef.current = [...deps]
404 } else {
405 // Original logic for config objects
406 collectionRef.current = createLiveQueryCollection({
407 startSync: true,
408 gcTime: DEFAULT_GC_TIME_MS,
409 ...configOrQueryOrCollection,
410 })
411 depsRef.current = [...deps]
412 }
413 }
414 }
415
416 // Reset refs when collection changes
417 if (needsNewCollection) {
418 versionRef.current = 0
419 snapshotRef.current = null
420 }
421
422 // Create stable subscribe function using ref
423 const subscribeRef = useRef<
424 ((onStoreChange: () => void) => () => void) | null
425 >(null)
426 if (!subscribeRef.current || needsNewCollection) {
427 subscribeRef.current = (onStoreChange: () => void) => {
428 // If no collection, return a no-op unsubscribe function
429 if (!collectionRef.current) {
430 return () => {}
431 }
432
433 let unsubscribed = false
434
435 const subscription = collectionRef.current.subscribeChanges(() => {
436 // Drop late notifies that race with unsubscribe.
437 if (unsubscribed) return
438 // Bump version on any change; getSnapshot will rebuild next time
439 versionRef.current += 1
440 onStoreChange()
441 })
442 // Already-ready collections won't emit an initial change. Notify React
443 // ourselves, but defer to a microtask — calling onStoreChange synchronously
444 // here lands during the render-to-commit window and trips React's
445 // "state update on a component that hasn't mounted yet" warning.
446 if (collectionRef.current.status === `ready`) {
447 queueMicrotask(() => {
448 if (unsubscribed) return
449 versionRef.current += 1
450 onStoreChange()
451 })
452 }
453 return () => {
454 unsubscribed = true
455 subscription.unsubscribe()
456 }
457 }
458 }
459
460 // Create stable getSnapshot function using ref
461 const getSnapshotRef = useRef<
462 | (() => {
463 collection: Collection<object, string | number, {}> | null
464 version: number
465 })
466 | null
467 >(null)
468 if (!getSnapshotRef.current || needsNewCollection) {
469 getSnapshotRef.current = () => {
470 const currentVersion = versionRef.current
471 const currentCollection = collectionRef.current
472
473 // Recreate snapshot object only if version/collection changed
474 if (
475 !snapshotRef.current ||
476 snapshotRef.current.version !== currentVersion ||
477 snapshotRef.current.collection !== currentCollection
478 ) {
479 snapshotRef.current = {
480 collection: currentCollection,
481 version: currentVersion,
482 }
483 }
484
485 return snapshotRef.current
486 }
487 }
488
489 // Use useSyncExternalStore to subscribe to collection changes
490 const snapshot = useSyncExternalStore(
491 subscribeRef.current,
492 getSnapshotRef.current,
493 )
494
495 // Track last snapshot (from useSyncExternalStore) and the returned value separately
496 const returnedSnapshotRef = useRef<{
497 collection: Collection<object, string | number, {}> | null
498 version: number
499 } | null>(null)
500 // Keep implementation return loose to satisfy overload signatures
501 const returnedRef = useRef<any>(null)
502
503 // Rebuild returned object only when the snapshot changes (version or collection identity)
504 if (
505 !returnedSnapshotRef.current ||
506 returnedSnapshotRef.current.version !== snapshot.version ||
507 returnedSnapshotRef.current.collection !== snapshot.collection
508 ) {
509 // Handle null collection case (when callback returns undefined/null)
510 if (!snapshot.collection) {
511 returnedRef.current = {
512 state: undefined,
513 data: undefined,
514 collection: undefined,
515 status: `disabled`,
516 isLoading: false,
517 isReady: true,
518 isIdle: false,
519 isError: false,
520 isCleanedUp: false,
521 isEnabled: false,
522 }
523 } else {
524 // Capture a stable view of entries for this snapshot to avoid tearing
525 const entries = Array.from(snapshot.collection.entries())
526 const singleResult = isSingleResultCollection(snapshot.collection)
527 let stateCache: Map<string | number, unknown> | null = null
528 let dataCache: Array<unknown> | null = null
529
530 returnedRef.current = {
531 get state() {
532 if (!stateCache) {
533 stateCache = new Map(entries)
534 }
535 return stateCache
536 },
537 get data() {
538 if (!dataCache) {
539 dataCache = entries.map(([, value]) => value)
540 }
541 return singleResult ? dataCache[0] : dataCache
542 },
543 collection: snapshot.collection,
544 status: snapshot.collection.status,
545 ...getLiveQueryStatusFlags(snapshot.collection.status),
546 isEnabled: true,
547 }
548 }
549
550 // Remember the snapshot that produced this returned value
551 returnedSnapshotRef.current = snapshot
552 }
553
554 return returnedRef.current!
555}