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

useLiveQuery.ts

1,066 lines35.5 KB

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