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