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

useLiveQuery.ts

1,043 lines33.5 KB

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