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