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

useLiveQuery.ts

1,072 lines33.5 KB

1'use client'
2​
3import { useRef, useSyncExternalStore } from 'react'
4import {
5 BaseQueryBuilder,
6 IR,
7 UnhashableQueryIRError,
8 createLiveQueryCollection,
9 createLiveQueryObserver,
10 deepEquals,
11 getPreparedLiveQueryIdentity,
12 getStableValueHash,
13 isCollection,
14 prepareLiveQueryValue,
15} from '@tanstack/db'
16import { useOptionalDbClient } from './DbProvider'
17import { setLiveQueryResultInfo } from './live-query-internals'
18import type {
19 Collection,
20 CollectionImpl,
21 CollectionStatus,
22 Context,
23 DbClient,
24 GetResult,
25 InferResultType,
26 InitialQueryBuilder,
27 LiveQueryCollectionConfig,
28 LiveQueryObserver,
29 LiveQueryPersistedStatus,
30 NonSingleResult,
31 QueryBuilder,
32 SingleResult,
33} from '@tanstack/db'
34​
35const DEFAULT_GC_TIME_MS = 1 // Live queries created by useLiveQuery are cleaned up immediately (0 disables GC)
36// Suspense renders can be abandoned before React subscribes. Keep their
37// collection briefly so a nearby retry can commit without starting over.
38const DEFAULT_SUSPENSE_GC_TIME_MS = 5000
39const DERIVED_IDENTITY_SINGLE_RENDER_WARN_MS = 16
40const DERIVED_IDENTITY_RENDER_COUNT_WARN_THRESHOLD = 10
41const DERIVED_IDENTITY_TOTAL_WARN_MS = 50
42const warnedDepsCallsites = new Set<string>()
43const warnedDerivedIdentityCallsites = new Set<string>()
44const warnedUnhashableIdentityCallsites = new Set<string>()
45const unpreparedQueryValue = Symbol(`unpreparedQueryValue`)
46​
47type SuspenseCollection = Collection<object, string | number, {}>
48type SuspenseCollectionEntry = {
49 collection: SuspenseCollection
50 removeStatusListeners: () => void
52​
53const unscopedSuspenseCollections = new Map<string, SuspenseCollectionEntry>()
54const suspenseCollectionsByClient = new WeakMap<
55 DbClient,
56 Map<string, SuspenseCollectionEntry>
57>()
58const suspenseSourceIds = new WeakMap<object, number>()
59let nextSuspenseSourceId = 0
60​
61function getSuspenseSourceId(source: object): number {
62 let id = suspenseSourceIds.get(source)
63 if (id === undefined) {
64 id = ++nextSuspenseSourceId
65 suspenseSourceIds.set(source, id)
66 }
67 return id
69​
70function getUnscopedSuspenseKey(
71 preparedValue: unknown,
72 queryHash: string,
73): string {
74 const query =
75 preparedValue instanceof BaseQueryBuilder
76 ? preparedValue
77 : preparedValue &&
78 typeof preparedValue === `object` &&
79 `query` in preparedValue &&
80 preparedValue.query instanceof BaseQueryBuilder
81 ? preparedValue.query
82 : undefined
83 if (!query) return queryHash
84 const sourceIds = IR.collectCollectionSources(query._getQuery()).map(
85 ({ collection }) => getSuspenseSourceId(collection),
86 )
87 return `${sourceIds.join(`,`)}:${queryHash}`
89​
90function getSuspenseCollections(
91 client: DbClient | undefined,
92): Map<string, SuspenseCollectionEntry> {
93 if (!client) return unscopedSuspenseCollections
94 let collections = suspenseCollectionsByClient.get(client)
95 if (!collections) {
96 collections = new Map()
97 suspenseCollectionsByClient.set(client, collections)
98 }
99 return collections
101​
102function releaseSuspenseCollection(
103 collections: Map<string, SuspenseCollectionEntry>,
104 queryHash: string,
105 collection: SuspenseCollection,
106): void {
107 const entry = collections.get(queryHash)
108 if (entry?.collection !== collection) return
109 collections.delete(queryHash)
110 entry.removeStatusListeners()
112​
113export type DerivedIdentityProfiler = {
114 renderCount: number
115 totalMs: number
116 maxMs: number
117 warned: boolean
119​
120export type UseLiveQueryStatus = CollectionStatus | `disabled`
121export type LiveQueryKey = ReadonlyArray<unknown>
122type UseLiveQueryConfigOptions<TContext extends Context> = Omit<
123 LiveQueryCollectionConfig<TContext>,
124 `query`
125> & {
126 /**
127 * Explicit identity for queries that contain opaque functional variants or
128 * are hot enough that deriving identity from structured IR is too expensive.
129 * Structured queries should omit this so DB can derive identity directly.
130 */
131 queryKey?: LiveQueryKey
132 /** Override the nearest DbProvider for this query. */
133 client?: DbClient
135​
136type ConfiguredQueryBuilder<TContext extends Context> = Extract<
137 LiveQueryCollectionConfig<TContext>[`query`],
138 QueryBuilder<TContext>
140​
141export type UseLiveQueryConfig<TContext extends Context> =
142 UseLiveQueryConfigOptions<TContext> &
143 Pick<LiveQueryCollectionConfig<TContext>, `query`>
144​
145export type ConditionalUseLiveQueryConfig<TContext extends Context> =
146 UseLiveQueryConfigOptions<TContext> & {
147 query:
148 | ConfiguredQueryBuilder<TContext>
149 | ((
150 q: InitialQueryBuilder,
151 ) => ConfiguredQueryBuilder<TContext> | undefined | null)
152 }
153​
154export function warnDeprecatedDepsArray(
155 hookName: `useLiveQuery` | `useLiveInfiniteQuery` = `useLiveQuery`,
156): void {
157 if (!shouldWarnInDevelopment(`TANSTACK_DB_DISABLE_DEPRECATION_WARNINGS`)) {
158 return
159 }
160​
161 const callsite = getWarningCallsite(4)
162 if (warnedDepsCallsites.has(callsite)) {
163 return
164 }
165 warnedDepsCallsites.add(callsite)
166 const replacement =
167 hookName === `useLiveQuery`
168 ? `useLiveQuery({ query })`
169 : `useLiveInfiniteQuery(query, { queryKey })`
170 console.warn(
171 `[${hookName}] The dependency-array form is deprecated and will be removed in 1.0. Use ${replacement} instead. Provide queryKey only for functional/opaque queries or to avoid deriving identity from structured query IR on render.`,
172 )
174​
175function shouldWarnInDevelopment(disableEnvVar: string): boolean {
176 if (typeof process === `undefined`) {
177 return false
178 }
179​
180 return (
181 process.env.NODE_ENV !== `production` && process.env[disableEnvVar] !== `1`
182 )
184​
185function getCurrentTime(): number {
186 return typeof performance !== `undefined` &&
187 typeof performance.now === `function`
188 ? performance.now()
189 : Date.now()
191​
192function getWarningCallsite(stackIndex: number): string {
193 const stack = new Error().stack ?? `unknown`
194 const lines = stack.split(`\n`)
195 const userFrame = lines
196 .slice(1)
197 .find(
198 (line) =>
199 !line.includes(`useLiveQuery.ts`) &&
200 !line.includes(`useLiveSuspenseQuery.ts`) &&
201 !line.includes(`useLiveInfiniteQuery.ts`),
202 )
203 return userFrame?.trim() ?? lines[stackIndex]?.trim() ?? stack
205​
206function warnDerivedIdentityHotPath(
207 profiler: DerivedIdentityProfiler,
208 durationMs: number,
209): void {
210 if (
211 profiler.warned ||
212 !shouldWarnInDevelopment(`TANSTACK_DB_DISABLE_QUERY_IDENTITY_WARNINGS`)
213 ) {
214 return
215 }
216​
217 const isSlowSingleRender =
218 durationMs >= DERIVED_IDENTITY_SINGLE_RENDER_WARN_MS
219 const isHotRenderPath =
220 profiler.renderCount >= DERIVED_IDENTITY_RENDER_COUNT_WARN_THRESHOLD &&
221 profiler.totalMs >= DERIVED_IDENTITY_TOTAL_WARN_MS
222​
223 if (!isSlowSingleRender && !isHotRenderPath) {
224 return
225 }
226​
227 const callsite = getWarningCallsite(5)
228 if (warnedDerivedIdentityCallsites.has(callsite)) {
229 profiler.warned = true
230 return
231 }
232​
233 warnedDerivedIdentityCallsites.add(callsite)
234 profiler.warned = true
235​
236 const reason = isSlowSingleRender
237 ? `one render took ${durationMs.toFixed(1)}ms`
238 : `${profiler.renderCount} renders took ${profiler.totalMs.toFixed(1)}ms`
239​
240 console.warn(
241 `[useLiveQuery] Deriving live query identity from structured query IR is running on a hot render path (${reason}, max ${profiler.maxMs.toFixed(1)}ms). ` +
242 `Provide an explicit queryKey to skip rebuilding and hashing the IR on every render: useLiveQuery({ queryKey: [...], query }).`,
243 )
245​
246function getExplicitQueryKey(value: unknown): LiveQueryKey | undefined {
247 return value &&
248 typeof value === `object` &&
249 Array.isArray((value as { queryKey?: unknown }).queryKey)
250 ? (value as { queryKey: LiveQueryKey }).queryKey
251 : undefined
253​
254function getExplicitDbClient(value: unknown): DbClient | undefined {
255 return value &&
256 typeof value === `object` &&
257 `client` in value &&
258 (value as { client?: unknown }).client !== undefined
259 ? (value as { client: DbClient }).client
260 : undefined
262​
263export function prepareQueryValue(
264 value: unknown,
265 dbClient: DbClient | undefined,
266 deferredCollections: Set<CollectionImpl<any, string | number, any, any, any>>,
267): unknown {
268 return prepareLiveQueryValue(value, dbClient, deferredCollections)
270​
271type DerivedQueryPreparation =
272 | {
273 status: `hashable`
274 value: unknown
275 identityDeps: Array<unknown>
276 }
277 | {
278 status: `unhashable`
279 value: unknown
280 error: UnhashableQueryIRError
281 }
282​
283export function prepareDerivedQuery(
284 value: unknown,
285 dbClient: DbClient | undefined,
286 profiler: DerivedIdentityProfiler,
287 deferredCollections: Set<CollectionImpl<any, string | number, any, any, any>>,
288): DerivedQueryPreparation {
289 const shouldProfile = shouldWarnInDevelopment(
290 `TANSTACK_DB_DISABLE_QUERY_IDENTITY_WARNINGS`,
291 )
292 const start = shouldProfile ? getCurrentTime() : 0
293 const preparedValue = prepareQueryValue(value, dbClient, deferredCollections)
294​
295 try {
296 const identity = getPreparedLiveQueryIdentity(preparedValue)
297 return {
298 status: `hashable`,
299 value: preparedValue,
300 identityDeps: [`derived`, identity],
301 }
302 } catch (error) {
303 if (error instanceof UnhashableQueryIRError) {
304 return { status: `unhashable`, value: preparedValue, error }
305 }
306​
307 throw error
308 } finally {
309 if (shouldProfile) {
310 const durationMs = getCurrentTime() - start
311 profiler.renderCount += 1
312 profiler.totalMs += durationMs
313 profiler.maxMs = Math.max(profiler.maxMs, durationMs)
314 warnDerivedIdentityHotPath(profiler, durationMs)
315 }
316 }
318​
319export function warnUnhashableDerivedIdentity(
320 error: UnhashableQueryIRError,
321): void {
322 if (!shouldWarnInDevelopment(`TANSTACK_DB_DISABLE_QUERY_IDENTITY_WARNINGS`)) {
323 return
324 }
325​
326 const callsite = getWarningCallsite(4)
327 if (warnedUnhashableIdentityCallsites.has(callsite)) {
328 return
329 }
330 warnedUnhashableIdentityCallsites.add(callsite)
331​
332 console.warn(
333 `[useLiveQuery] This query cannot derive a stable identity because ${error.reason} at ${error.path}. ` +
334 `It will keep the legacy mount-stable behavior for now. Add queryKey: [...] to make captured values reactive. ` +
335 `Unhashable queries without queryKey will throw in 1.0.`,
336 )
338​
339function createCollectionFromPreparedQuery(
340 value: unknown,
341 defaultGcTime = DEFAULT_GC_TIME_MS,
342) {
343 if (value === undefined || value === null) {
344 return null
345 }
346​
347 if (isCollection(value)) {
348 value.startSyncImmediate()
349 return value
350 }
351​
352 if (value instanceof BaseQueryBuilder) {
353 return createLiveQueryCollection({
354 query: value,
355 startSync: true,
356 gcTime: defaultGcTime,
357 })
358 }
359​
360 if (typeof value === `object`) {
361 return createLiveQueryCollection({
362 startSync: true,
363 gcTime: defaultGcTime,
364 ...(value as LiveQueryCollectionConfig<any>),
365 })
366 }
367​
368 throw new Error(
369 `useLiveQuery callback must return a QueryBuilder, LiveQueryCollectionConfig, Collection, undefined, or null. Got: ${typeof value}`,
370 )
372​
373/**
374 * Create a live query using a query function.
375 * @param queryFn - Query function that defines what data to fetch
376 * @param deps - Deprecated array of dependencies that trigger query re-execution when changed
377 * @returns Object with reactive data, state, and status information
378 * @example
379 * // Prefer config object syntax
380 * const { data, isLoading } = useLiveQuery({
381 * query: (q) =>
382 * q.from({ todos: todosCollection })
383 * .where(({ todos }) => eq(todos.completed, false))
384 * .select(({ todos }) => ({ id: todos.id, text: todos.text }))
385 * })
386 *
387 * @example
388 * // Single result query
389 * const { data } = useLiveQuery({
390 * query: (q) => q.from({ todos: todosCollection })
391 * .where(({ todos }) => eq(todos.id, 1))
392 * .findOne()
393 * })
394 *
395 * @example
396 * // Structured captured values are included in derived query identity
397 * const { data, state } = useLiveQuery({
398 * query: (q) => q.from({ todos: todosCollection })
399 * .where(({ todos }) => gt(todos.priority, minPriority)),
400 * })
401 *
402 * @example
403 * // Return undefined or null to disable a query
404 * const { data, isEnabled } = useLiveQuery({
405 * query: (q) => {
406 * if (!userId) return undefined
407 * return q.from({ todos: todosCollection })
408 * .where(({ todos }) => eq(todos.userId, userId))
409 * },
410 * })
411 *
412 * @example
413 * // Join pattern
414 * const { data } = useLiveQuery({
415 * query: (q) =>
416 * q.from({ issues: issueCollection })
417 * .join({ persons: personCollection }, ({ issues, persons }) =>
418 * eq(issues.userId, persons.id)
419 * )
420 * .select(({ issues, persons }) => ({
421 * id: issues.id,
422 * title: issues.title,
423 * userName: persons.name
424 * }))
425 * })
426 *
427 * @example
428 * // Handle loading and error states
429 * const { data, isLoading, isError, status } = useLiveQuery({
430 * query: (q) => q.from({ todos: todoCollection })
431 * })
432 *
433 * if (isLoading) return <div>Loading...</div>
434 * if (isError) return <div>Error: {status}</div>
435 *
436 * return (
437 * <ul>
438 * {data.map(todo => <li key={todo.id}>{todo.text}</li>)}
439 * </ul>
440 * )
441 */
442// Overload 1: Accept query function that always returns QueryBuilder
443export function useLiveQuery<TContext extends Context>(
444 queryFn: (q: InitialQueryBuilder) => QueryBuilder<TContext>,
445 deps?: Array<unknown>,
446): {
447 state: Map<string | number, GetResult<TContext>>
448 data: InferResultType<TContext>
449 collection: Collection<GetResult<TContext>, string | number, {}>
450 status: CollectionStatus // Can't be disabled if always returns QueryBuilder
451 isLoading: boolean
452 isReady: boolean
453 persistedStatus: LiveQueryPersistedStatus
454 isPersistedReady: boolean
455 persistedError: unknown | undefined
456 isIdle: boolean
457 isError: boolean
458 isCleanedUp: boolean
459 isEnabled: true // Always true if always returns QueryBuilder
461​
462// Overload 2: Accept query function that can return undefined/null
463export function useLiveQuery<TContext extends Context>(
464 queryFn: (
465 q: InitialQueryBuilder,
466 ) => QueryBuilder<TContext> | undefined | null,
467 deps?: Array<unknown>,
468): {
469 state: Map<string | number, GetResult<TContext>> | undefined
470 data: InferResultType<TContext> | undefined
471 collection: Collection<GetResult<TContext>, string | number, {}> | undefined
472 status: UseLiveQueryStatus
473 isLoading: boolean
474 isReady: boolean
475 persistedStatus: LiveQueryPersistedStatus
476 isPersistedReady: boolean
477 persistedError: unknown | undefined
478 isIdle: boolean
479 isError: boolean
480 isCleanedUp: boolean
481 isEnabled: boolean
483​
484// Overload 3: Accept query function that can return LiveQueryCollectionConfig
485export function useLiveQuery<TContext extends Context>(
486 queryFn: (
487 q: InitialQueryBuilder,
488 ) => LiveQueryCollectionConfig<TContext> | undefined | null,
489 deps?: Array<unknown>,
490): {
491 state: Map<string | number, GetResult<TContext>> | undefined
492 data: InferResultType<TContext> | undefined
493 collection: Collection<GetResult<TContext>, string | number, {}> | undefined
494 status: UseLiveQueryStatus
495 isLoading: boolean
496 isReady: boolean
497 persistedStatus: LiveQueryPersistedStatus
498 isPersistedReady: boolean
499 persistedError: unknown | undefined
500 isIdle: boolean
501 isError: boolean
502 isCleanedUp: boolean
503 isEnabled: boolean
505​
506// Overload 4: Accept query function that can return Collection
507export function useLiveQuery<
508 TResult extends object,
509 TKey extends string | number,
510 TUtils extends Record<string, any>,
511>(
512 queryFn: (
513 q: InitialQueryBuilder,
514 ) => Collection<TResult, TKey, TUtils> | undefined | null,
515 deps?: Array<unknown>,
516): {
517 state: Map<TKey, TResult> | undefined
518 data: Array<TResult> | undefined
519 collection: Collection<TResult, TKey, TUtils> | undefined
520 status: UseLiveQueryStatus
521 isLoading: boolean
522 isReady: boolean
523 persistedStatus: LiveQueryPersistedStatus
524 isPersistedReady: boolean
525 persistedError: unknown | undefined
526 isIdle: boolean
527 isError: boolean
528 isCleanedUp: boolean
529 isEnabled: boolean
531​
532// Overload 5: Accept query function that can return all types
533export function useLiveQuery<
534 TContext extends Context,
535 TResult extends object,
536 TKey extends string | number,
537 TUtils extends Record<string, any>,
538>(
539 queryFn: (
540 q: InitialQueryBuilder,
541 ) =>
542 | QueryBuilder<TContext>
543 | LiveQueryCollectionConfig<TContext>
544 | Collection<TResult, TKey, TUtils>
545 | undefined
546 | null,
547 deps?: Array<unknown>,
548): {
549 state:
550 | Map<string | number, GetResult<TContext>>
551 | Map<TKey, TResult>
552 | undefined
553 data: InferResultType<TContext> | Array<TResult> | undefined
554 collection:
555 | Collection<GetResult<TContext>, string | number, {}>
556 | Collection<TResult, TKey, TUtils>
557 | undefined
558 status: UseLiveQueryStatus
559 isLoading: boolean
560 isReady: boolean
561 persistedStatus: LiveQueryPersistedStatus
562 isPersistedReady: boolean
563 persistedError: unknown | undefined
564 isIdle: boolean
565 isError: boolean
566 isCleanedUp: boolean
567 isEnabled: boolean
569​
570/**
571 * Create a live query using configuration object
572 * @param config - Configuration object with query and options
573 * @param deps - Deprecated array of dependencies that trigger query re-execution when changed
574 * @returns Object with reactive data, state, and status information
575 * @example
576 * // Basic config object usage
577 * const { data, status } = useLiveQuery({
578 * query: (q) => q.from({ todos: todosCollection }),
579 * gcTime: 60000
580 * })
581 *
582 * @example
583 * // With query builder and options
584 * const queryBuilder = new Query()
585 * .from({ persons: collection })
586 * .where(({ persons }) => gt(persons.age, 30))
587 * .select(({ persons }) => ({ id: persons.id, name: persons.name }))
588 *
589 * const { data, isReady } = useLiveQuery({
590 * query: queryBuilder,
591 * })
592 *
593 * @example
594 * // Handle all states uniformly
595 * const { data, isLoading, isReady, isError } = useLiveQuery({
596 * query: (q) => q.from({ items: itemCollection })
597 * })
598 *
599 * if (isLoading) return <div>Loading...</div>
600 * if (isError) return <div>Something went wrong</div>
601 * if (!isReady) return <div>Preparing...</div>
602 *
603 * return <div>{data.length} items loaded</div>
604 */
605// Overload 6: Accept config object
606export function useLiveQuery<TContext extends Context>(
607 config: UseLiveQueryConfig<TContext>,
608): {
609 state: Map<string | number, GetResult<TContext>>
610 data: InferResultType<TContext>
611 collection: Collection<GetResult<TContext>, string | number, {}>
612 status: CollectionStatus // Can't be disabled when query always returns a builder
613 isLoading: boolean
614 isReady: boolean
615 persistedStatus: LiveQueryPersistedStatus
616 isPersistedReady: boolean
617 persistedError: unknown | undefined
618 isIdle: boolean
619 isError: boolean
620 isCleanedUp: boolean
621 isEnabled: true // Always true when query always returns a builder
623​
624// Overload 7: Accept config object with a query that can return undefined/null
625export function useLiveQuery<TContext extends Context>(
626 config: ConditionalUseLiveQueryConfig<TContext>,
627): {
628 state: Map<string | number, GetResult<TContext>> | undefined
629 data: InferResultType<TContext> | undefined
630 collection: Collection<GetResult<TContext>, string | number, {}> | undefined
631 status: UseLiveQueryStatus
632 isLoading: boolean
633 isReady: boolean
634 persistedStatus: LiveQueryPersistedStatus
635 isPersistedReady: boolean
636 persistedError: unknown | undefined
637 isIdle: boolean
638 isError: boolean
639 isCleanedUp: boolean
640 isEnabled: boolean
642​
643// Overload 8: Accept config object with legacy deps
644export function useLiveQuery<TContext extends Context>(
645 config: LiveQueryCollectionConfig<TContext>,
646 deps?: Array<unknown>,
647): {
648 state: Map<string | number, GetResult<TContext>>
649 data: InferResultType<TContext>
650 collection: Collection<GetResult<TContext>, string | number, {}>
651 status: CollectionStatus // Can't be disabled when query always returns a builder
652 isLoading: boolean
653 isReady: boolean
654 persistedStatus: LiveQueryPersistedStatus
655 isPersistedReady: boolean
656 persistedError: unknown | undefined
657 isIdle: boolean
658 isError: boolean
659 isCleanedUp: boolean
660 isEnabled: true // Always true when query always returns a builder
662​
663// Overload 9: Accept config object with legacy deps and a query that can return undefined/null
664export function useLiveQuery<TContext extends Context>(
665 config: ConditionalUseLiveQueryConfig<TContext>,
666 deps: Array<unknown>,
667): {
668 state: Map<string | number, GetResult<TContext>> | undefined
669 data: InferResultType<TContext> | undefined
670 collection: Collection<GetResult<TContext>, string | number, {}> | undefined
671 status: UseLiveQueryStatus
672 isLoading: boolean
673 isReady: boolean
674 persistedStatus: LiveQueryPersistedStatus
675 isPersistedReady: boolean
676 persistedError: unknown | undefined
677 isIdle: boolean
678 isError: boolean
679 isCleanedUp: boolean
680 isEnabled: boolean
682​
683/**
684 * Subscribe to an existing live query collection
685 * @param liveQueryCollection - Pre-created live query collection to subscribe to
686 * @returns Object with reactive data, state, and status information
687 * @example
688 * // Using pre-created live query collection
689 * const myLiveQuery = createLiveQueryCollection((q) =>
690 * q.from({ todos: todosCollection }).where(({ todos }) => eq(todos.active, true))
691 * )
692 * const { data, collection } = useLiveQuery(myLiveQuery)
693 *
694 * @example
695 * // Access collection methods directly
696 * const { data, collection, isReady } = useLiveQuery(existingCollection)
697 *
698 * // Use collection for mutations
699 * const handleToggle = (id) => {
700 * collection.update(id, draft => { draft.completed = !draft.completed })
701 * }
702 *
703 * @example
704 * // Handle states consistently
705 * const { data, isLoading, isError } = useLiveQuery(sharedCollection)
706 *
707 * if (isLoading) return <div>Loading...</div>
708 * if (isError) return <div>Error loading data</div>
709 *
710 * return <div>{data.map(item => <Item key={item.id} {...item} />)}</div>
711 */
712// Overload 10: Accept pre-created live query collection
713export function useLiveQuery<
714 TResult extends object,
715 TKey extends string | number,
716 TUtils extends Record<string, any>,
717>(
718 liveQueryCollection: Collection<TResult, TKey, TUtils> & NonSingleResult,
719): {
720 state: Map<TKey, TResult>
721 data: Array<TResult>
722 collection: Collection<TResult, TKey, TUtils>
723 status: CollectionStatus // Can't be disabled for pre-created live query collections
724 isLoading: boolean
725 isReady: boolean
726 persistedStatus: LiveQueryPersistedStatus
727 isPersistedReady: boolean
728 persistedError: unknown | undefined
729 isIdle: boolean
730 isError: boolean
731 isCleanedUp: boolean
732 isEnabled: true // Always true for pre-created live query collections
734​
735// Overload 10: Accept pre-created live query collection with singleResult: true
736export function useLiveQuery<
737 TResult extends object,
738 TKey extends string | number,
739 TUtils extends Record<string, any>,
740>(
741 liveQueryCollection: Collection<TResult, TKey, TUtils> & SingleResult,
742): {
743 state: Map<TKey, TResult>
744 data: TResult | undefined
745 collection: Collection<TResult, TKey, TUtils> & SingleResult
746 status: CollectionStatus // Can't be disabled for pre-created live query collections
747 isLoading: boolean
748 isReady: boolean
749 persistedStatus: LiveQueryPersistedStatus
750 isPersistedReady: boolean
751 persistedError: unknown | undefined
752 isIdle: boolean
753 isError: boolean
754 isCleanedUp: boolean
755 isEnabled: true // Always true for pre-created live query collections
757​
758// Implementation - use function overloads to infer the actual collection type
759export function useLiveQuery(
760 configOrQueryOrCollection: any,
761 deps?: Array<unknown>,
762) {
763 return useLiveQueryImpl(configOrQueryOrCollection, deps)
765​
766/** @internal Shared implementation for the Suspense wrapper. */
767export function useLiveQueryForSuspense(
768 configOrQueryOrCollection: any,
769 deps: Array<unknown> | undefined,
770) {
771 return useLiveQueryImpl(configOrQueryOrCollection, deps, true)
773​
774function useLiveQueryImpl(
775 configOrQueryOrCollection: any,
776 deps: Array<unknown> | undefined,
777 forSuspense = false,
778) {
779 const contextDbClient = useOptionalDbClient()
780 // Check if it's already a collection
781 const inputIsCollection = isCollection(configOrQueryOrCollection)
782 const dbClient = inputIsCollection
783 ? contextDbClient
784 : (getExplicitDbClient(configOrQueryOrCollection) ?? contextDbClient)
785 const resolvedDeps = deps ?? []
786​
787 // Use refs to cache collection and track dependencies
788 const collectionRef = useRef<Collection<object, string | number, {}> | null>(
789 null,
790 )
791 const depsRef = useRef<Array<unknown> | null>(null)
792 const configRef = useRef<unknown>(null)
793 const clientRef = useRef(dbClient)
794 const legacyUnhashableIdentityRef = useRef<Array<unknown>>([
795 `legacy-unhashable`,
796 ])
797​
798 const derivedIdentityProfilerRef = useRef<DerivedIdentityProfiler>({
799 renderCount: 0,
800 totalMs: 0,
801 maxMs: 0,
802 warned: false,
803 })
804 const deferredCollectionsRef = useRef(
805 new Set<CollectionImpl<any, string | number, any, any, any>>(),
806 )
807 const observerRef = useRef<LiveQueryObserver<object, string | number> | null>(
808 null,
809 )
810 const queryHashRef = useRef<string | undefined>(undefined)
811 const suspenseKeyRef = useRef<string | undefined>(undefined)
812 const identityErrorRef = useRef<UnhashableQueryIRError | undefined>(undefined)
813​
814 const queryKey = !inputIsCollection
815 ? getExplicitQueryKey(configOrQueryOrCollection)
816 : undefined
817 let preparedQueryValue: unknown | typeof unpreparedQueryValue =
818 unpreparedQueryValue
819 let identityDeps: ReadonlyArray<unknown>
820 let streamIdentity: unknown = undefined
821 let identityError: UnhashableQueryIRError | undefined
822​
823 if (queryKey) {
824 identityDeps = queryKey
825 streamIdentity = [`queryKey`, queryKey]
826 } else if (deps !== undefined) {
827 identityDeps = resolvedDeps
828 try {
829 preparedQueryValue = prepareQueryValue(
830 configOrQueryOrCollection,
831 dbClient,
832 deferredCollectionsRef.current,
833 )
834 streamIdentity = [
835 `deps`,
836 resolvedDeps,
837 getPreparedLiveQueryIdentity(preparedQueryValue),
838 ]
839 } catch (error) {
840 if (!(error instanceof UnhashableQueryIRError)) throw error
841 warnUnhashableDerivedIdentity(error)
842 identityError = error
843 }
844 } else if (inputIsCollection) {
845 identityDeps = []
846 streamIdentity = [`collection`, configOrQueryOrCollection.id]
847 } else {
848 const preparation = prepareDerivedQuery(
849 configOrQueryOrCollection,
850 dbClient,
851 derivedIdentityProfilerRef.current,
852 deferredCollectionsRef.current,
853 )
854 preparedQueryValue = preparation.value
855 if (preparation.status === `hashable`) {
856 identityDeps = preparation.identityDeps
857 streamIdentity = preparation.identityDeps
858 } else {
859 warnUnhashableDerivedIdentity(preparation.error)
860 identityDeps = legacyUnhashableIdentityRef.current
861 identityError = preparation.error
862 }
863 }
864​
865 let queryHash: string | undefined
866 if (streamIdentity !== undefined) {
867 try {
868 queryHash = getStableValueHash(streamIdentity, `queryKey`)
869 } catch (error) {
870 if (error instanceof UnhashableQueryIRError) {
871 if (queryKey !== undefined) throw error
872 identityError = error
873 } else {
874 throw error
875 }
876 }
877 }
878​
879 if (deps !== undefined) {
880 warnDeprecatedDepsArray()
881 }
882​
883 const canReuseSuspenseKey =
884 forSuspense &&
885 !inputIsCollection &&
886 queryHash !== undefined &&
887 !dbClient &&
888 collectionRef.current !== null &&
889 clientRef.current === dbClient &&
890 queryHashRef.current === queryHash &&
891 suspenseKeyRef.current !== undefined
892​
893 if (
894 forSuspense &&
895 !inputIsCollection &&
896 queryHash &&
897 !dbClient &&
898 !canReuseSuspenseKey &&
899 preparedQueryValue === unpreparedQueryValue
900 ) {
901 preparedQueryValue = prepareQueryValue(
902 configOrQueryOrCollection,
903 dbClient,
904 deferredCollectionsRef.current,
905 )
906 }
907​
908 const suspenseKey =
909 queryHash && !dbClient
910 ? canReuseSuspenseKey
911 ? suspenseKeyRef.current
912 : getUnscopedSuspenseKey(preparedQueryValue, queryHash)
913 : queryHash
914​
915 const suspenseCollections =
916 forSuspense && !inputIsCollection && suspenseKey
917 ? getSuspenseCollections(dbClient)
918 : undefined
919 const suspenseEntry = suspenseKey
920 ? suspenseCollections?.get(suspenseKey)
921 : undefined
922 const suspenseCollection = suspenseEntry?.collection
923​
924 const identityChanged =
925 depsRef.current === null ||
926 (deps !== undefined
927 ? depsRef.current.length !== identityDeps.length ||
928 depsRef.current.some((dep, index) => dep !== identityDeps[index])
929 : !deepEquals(depsRef.current, identityDeps))
930​
931 // Check if we need to create/recreate the collection
932 const needsNewCollection =
933 !collectionRef.current ||
934 (inputIsCollection && configRef.current !== configOrQueryOrCollection) ||
935 (!inputIsCollection && (clientRef.current !== dbClient || identityChanged))
936​
937 const resumeDeferredCollections = () => {
938 for (const collection of deferredCollectionsRef.current) {
939 collection._resumeSyncStart()
940 }
941 deferredCollectionsRef.current.clear()
942 }
943​
944 if (needsNewCollection) {
945 if (inputIsCollection) {
946 // Warn when passing a collection directly with on-demand sync mode
947 // In on-demand mode, data is only loaded when queries with predicates request it
948 // Passing the collection directly doesn't provide any predicates, so no data loads
949 const syncMode = (
950 configOrQueryOrCollection as { config?: { syncMode?: string } }
951 ).config?.syncMode
952 if (
953 syncMode === `on-demand` &&
954 shouldWarnInDevelopment(`TANSTACK_DB_DISABLE_QUERY_IDENTITY_WARNINGS`)
955 ) {
956 console.warn(
957 `[useLiveQuery] Warning: Passing a collection with syncMode "on-demand" directly to useLiveQuery ` +
958 `will not load any data. In on-demand mode, data is only loaded when queries with predicates request it.\n\n` +
959 `Instead, use a query builder function:\n` +
960 ` const { data } = useLiveQuery({ query: (q) => q.from({ c: myCollection }).select(({ c }) => c) })\n\n` +
961 `Or switch to syncMode "eager" if you want all data to sync automatically.`,
962 )
963 }
964 // It's already a collection, ensure sync is started for React hooks
965 configOrQueryOrCollection.startSyncImmediate()
966 collectionRef.current = configOrQueryOrCollection
967 configRef.current = configOrQueryOrCollection
968 } else {
969 if (suspenseCollection) {
970 collectionRef.current = suspenseCollection
971 } else {
972 if (preparedQueryValue === unpreparedQueryValue) {
973 preparedQueryValue = prepareQueryValue(
974 configOrQueryOrCollection,
975 dbClient,
976 deferredCollectionsRef.current,
977 )
978 }
979 collectionRef.current = createCollectionFromPreparedQuery(
980 preparedQueryValue,
981 forSuspense ? DEFAULT_SUSPENSE_GC_TIME_MS : DEFAULT_GC_TIME_MS,
982 ) as SuspenseCollection | null
983 if (suspenseCollections && suspenseKey && collectionRef.current) {
984 const collection = collectionRef.current
985 const removeCleanupListener = collection.on(`status:cleaned-up`, () =>
986 releaseSuspenseCollection(
987 suspenseCollections,
988 suspenseKey,
989 collection,
990 ),
991 )
992 const removeErrorListener = collection.on(`status:error`, () => {
993 // Keep the failed collection through React's immediate retry so
994 // the hook can throw its actual load error to an ErrorBoundary.
995 // Retire it afterward so a later boundary reset starts fresh.
996 setTimeout(
997 () =>
998 releaseSuspenseCollection(
999 suspenseCollections,
1000 suspenseKey,
1001 collection,
1002 ),
1003 0,
1005 })
1006 const entry: SuspenseCollectionEntry = {
1007 collection,
1008 removeStatusListeners: () => {
1009 removeCleanupListener()
1010 removeErrorListener()
1011 },
1013 suspenseCollections.set(suspenseKey, entry)
1016 configRef.current = configOrQueryOrCollection
1017 depsRef.current = [...identityDeps]
1019 clientRef.current = dbClient
1020 queryHashRef.current = queryHash
1021 suspenseKeyRef.current = suspenseKey
1022 identityErrorRef.current = identityError
1024​
1025 // Recreate the observer when the underlying collection changes. The observer
1026 // is not disposed explicitly here or on unmount: `useSyncExternalStore`
1027 // unsubscribes it when the subscribe changes or the component unmounts, which
1028 // detaches the collection subscription; the observer is then GC'd. (An unmount
1029 // effect that disposed it would misfire under StrictMode/offscreen effect
1030 // replay, leaving a disposed observer in the ref.)
1031 if (needsNewCollection) {
1032 // Defer the initial notify: useSyncExternalStore must not be notified
1033 // synchronously during subscribe.
1034 // Wholesale mode: React re-reads getSnapshot() on notify, keeps the
1035 // hook's pre-observer loading policy, and — because wholesale delivers
1036 // nothing synchronously during subscribe — never notifies
1037 // useSyncExternalStore inside its own subscribe call.
1038 observerRef.current = createLiveQueryObserver(collectionRef.current, {
1039 mode: `wholesale`,
1040 client: dbClient,
1041 queryHash: queryHashRef.current,
1042 onPreload: resumeDeferredCollections,
1043 })
1045 const observer = observerRef.current!
1046​
1047 // Stable subscribe bound to the current observer; the observer owns the
1048 // subscription, ready-race, and disposal.
1049 const subscribeRef = useRef<
1050 ((onStoreChange: () => void) => () => void) | null
1051 >(null)
1052 if (!subscribeRef.current || needsNewCollection) {
1053 subscribeRef.current = (onStoreChange: () => void) => {
1054 const unsubscribe = observer.subscribe(() => onStoreChange())
1055 resumeDeferredCollections()
1056 return unsubscribe
1059​
1060 const returned = useSyncExternalStore(
1061 subscribeRef.current,
1062 () => observer.getSnapshot(),
1063 () => observer.getServerSnapshot(),
1065 setLiveQueryResultInfo(returned, {
1066 client: dbClient,
1067 queryHash: queryHashRef.current,
1068 identityError: identityErrorRef.current,
1069 observer,
1070 })
1071 return returned as any