Open History to see the last commit
1'use client'
2
3import { useCallback, useRef, useSyncExternalStore } from 'react'
4import {
5 assertLiveQueryWindowManyResult,
6 compareLiveQueryWindowDependencies,
7 createLiveQueryCollection,
8 createLiveQueryWindowController,
9 fetchNextLiveQueryWindowPage,
10 getLiveQueryWindowCollectionWarning,
11 getLiveQueryWindowInputKind,
12 normalizeLiveQueryWindowPageSize,
13 resolveLiveQueryWindowInput,
14 shouldPreserveLiveQueryWindowPageCount,
15} from '@tanstack/db'
16import { useOptionalDbClient } from './DbProvider'
17import {
18 prepareDerivedQuery,
19 prepareQueryValue,
20 warnDeprecatedDepsArray,
21 warnUnhashableDerivedIdentity,
22} from './useLiveQuery'
23import type {
24 DerivedIdentityProfiler,
25 LiveQueryKey,
26 useLiveQuery,
27} from './useLiveQuery'
28import type {
29 Collection,
30 CollectionImpl as CollectionImplType,
31 CollectionStatus,
32 Context,
33 DbClient,
34 InferResultType,
35 InitialQueryBuilder,
36 LiveQueryPersistedStatus,
37 LiveQueryWindowController,
38 NonSingleResult,
39 QueryBuilder,
40} from '@tanstack/db'
41
42// Live queries created here are cleaned up immediately (0 disables GC).
43const DEFAULT_GC_TIME_MS = 1
44const unpreparedQueryValue = Symbol(`unpreparedQueryValue`)
45
46// Keep the generic parameter for existing typed config wrappers.
47export type UseLiveInfiniteQueryConfig<_TContext extends Context> = {
48 /**
49 * Explicit identity for queries that contain opaque functional variants or
50 * are hot enough that deriving identity from structured IR is too expensive.
51 * Structured queries should omit this so DB can derive identity directly.
52 */
53 queryKey?: LiveQueryKey
54 /** Override the nearest DbProvider for this query. */
55 client?: DbClient
56 pageSize?: number
57 /** First result-page label, not a server cursor or remote offset. */
58 initialPageParam?: number
59}
60
61export type UseLiveInfiniteQueryReturn<TContext extends Context> = Omit<
62 ReturnType<typeof useLiveQuery<TContext>>,
63 `data`
64> & {
65 data: InferResultType<TContext>
66 pages: Array<Array<InferResultType<TContext>[number]>>
67 pageParams: Array<number>
68 fetchNextPage: () => Promise<void>
69 hasNextPage: boolean
70 isFetchingNextPage: boolean
71 error: unknown
72}
73
74export type UseLiveInfiniteQueryReturnWithCollection<
75 TResult extends object,
76 TKey extends string | number,
77 TUtils extends Record<string, any>,
78> = {
79 data: Array<TResult>
80 state: Map<TKey, TResult>
81 collection: Collection<TResult, TKey, TUtils> & NonSingleResult
82 status: CollectionStatus
83 isLoading: boolean
84 isReady: boolean
85 persistedStatus: LiveQueryPersistedStatus
86 isPersistedReady: boolean
87 persistedError: unknown | undefined
88 isIdle: boolean
89 isError: boolean
90 isCleanedUp: boolean
91 isEnabled: true
92 pages: Array<Array<TResult>>
93 pageParams: Array<number>
94 fetchNextPage: () => Promise<void>
95 hasNextPage: boolean
96 isFetchingNextPage: boolean
97 error: unknown
98}
99
100type EnabledLiveQueryReturn<TContext extends Context> = ReturnType<
101 typeof useLiveQuery<TContext>
102>
103
104type InfiniteQueryRenderState = {
105 inputKind: `collection` | `query`
106 inputCollection: Collection<any, any, any> | null
107 inputQuery: unknown
108 client: DbClient | undefined
109 identityMode: `collection` | `queryKey` | `legacyDeps` | `derived`
110 dependencies: Array<unknown> | null
111 pageSize: number
112 initialPageParam: number
113 collection: Collection<any, any, any>
114 controller: LiveQueryWindowController<any, any>
115 warning: string | null
116 warned: boolean
117 deferredCollections: Set<
118 CollectionImplType<any, string | number, any, any, any>
119 >
120}
121
122/**
123 * Create an infinite query using a query function with live updates.
124 *
125 * Uses `utils.setWindow()` to dynamically adjust the limit/offset window
126 * without recreating the live query collection on each page change.
127 *
128 * @param queryFn - Query function that defines what data to fetch. Must include `.orderBy()` for setWindow to work.
129 * @param config - Configuration including pageSize and an optional initial page label
130 * @param deps - Deprecated array of dependencies that trigger query re-execution when changed
131 * @returns Object with pages, data, and pagination controls
132 */
133
134// Overload for pre-created collection (non-single result)
135export function useLiveInfiniteQuery<
136 TResult extends object,
137 TKey extends string | number,
138 TUtils extends Record<string, any>,
139>(
140 liveQueryCollection: Collection<TResult, TKey, TUtils> & NonSingleResult,
141 config: UseLiveInfiniteQueryConfig<any>,
142): UseLiveInfiniteQueryReturnWithCollection<TResult, TKey, TUtils>
143
144// Overload for query function
145export function useLiveInfiniteQuery<TContext extends Context>(
146 queryFn: (q: InitialQueryBuilder) => QueryBuilder<TContext>,
147 config: UseLiveInfiniteQueryConfig<TContext>,
148 deps?: Array<unknown>,
149): UseLiveInfiniteQueryReturn<TContext>
150
151// Implementation
152export function useLiveInfiniteQuery<TContext extends Context>(
153 queryFnOrCollection: any,
154 config: UseLiveInfiniteQueryConfig<TContext>,
155 deps?: Array<unknown>,
156): UseLiveInfiniteQueryReturn<TContext> {
157 if (`getNextPageParam` in config) {
158 throw new Error(
159 `getNextPageParam is not supported by useLiveInfiniteQuery. Use an on-demand collection and fulfill meta.loadSubsetOptions in queryFn for server pagination.`,
160 )
161 }
162 const pageSize = normalizeLiveQueryWindowPageSize(config.pageSize)
163 const initialPageParam = config.initialPageParam ?? 0
164 const contextDbClient = useOptionalDbClient()
165 const dbClient = config.client ?? contextDbClient
166
167 const inputIsCollection =
168 getLiveQueryWindowInputKind(queryFnOrCollection) === `collection`
169
170 const committedRef = useRef<InfiniteQueryRenderState | null>(null)
171 const committed = committedRef.current
172 // The previous render's state. A second pre-commit render (React StrictMode,
173 // a discarded concurrent render, or a Suspense retry) reuses the collection
174 // it already built instead of starting a duplicate sync. Unlike
175 // `committedRef`, an abandoned render may update this; it only ever gates a
176 // same-identity reuse, never page preservation.
177 const renderedRef = useRef<InfiniteQueryRenderState | null>(null)
178 const rendered = renderedRef.current
179 const inputKind = inputIsCollection ? `collection` : `query`
180 const derivedIdentityProfilerRef = useRef<DerivedIdentityProfiler>({
181 renderCount: 0,
182 totalMs: 0,
183 maxMs: 0,
184 warned: false,
185 })
186 const legacyUnhashableIdentityRef = useRef<Array<unknown>>([
187 `legacy-unhashable`,
188 ])
189 const deferredCollections = new Set<
190 CollectionImplType<any, string | number, any, any, any>
191 >()
192
193 let preparedQueryValue: unknown | typeof unpreparedQueryValue =
194 unpreparedQueryValue
195 let identityDeps: ReadonlyArray<unknown> = []
196 let identityMode: InfiniteQueryRenderState[`identityMode`] = `collection`
197
198 if (!inputIsCollection) {
199 if (config.queryKey !== undefined) {
200 identityMode = `queryKey`
201 identityDeps = config.queryKey
202 } else if (deps !== undefined) {
203 identityMode = `legacyDeps`
204 identityDeps = deps
205 warnDeprecatedDepsArray(`useLiveInfiniteQuery`)
206 } else if (
207 committed?.identityMode === `derived` &&
208 committed.inputQuery === queryFnOrCollection &&
209 committed.client === dbClient
210 ) {
211 identityMode = `derived`
212 identityDeps = committed.dependencies ?? []
213 } else {
214 identityMode = `derived`
215 const preparation = prepareDerivedQuery(
216 queryFnOrCollection,
217 dbClient,
218 derivedIdentityProfilerRef.current,
219 deferredCollections,
220 )
221 preparedQueryValue = preparation.value
222 if (preparation.status === `hashable`) {
223 identityDeps = preparation.identityDeps
224 } else {
225 warnUnhashableDerivedIdentity(preparation.error)
226 identityDeps = legacyUnhashableIdentityRef.current
227 }
228 }
229 }
230
231 const usesLegacyDeps =
232 !inputIsCollection && config.queryKey === undefined && deps !== undefined
233 const dependencyComparison = compareLiveQueryWindowDependencies(
234 committed?.dependencies,
235 identityDeps,
236 )
237 const sameClient = committed?.client === dbClient
238 const dependenciesChanged =
239 !inputIsCollection &&
240 (!sameClient ||
241 (usesLegacyDeps
242 ? dependencyComparison.changed
243 : !dependencyComparison.structurallyEqual))
244 const dependenciesStructurallyEqual =
245 usesLegacyDeps && sameClient && dependencyComparison.structurallyEqual
246 const needsNewCollection =
247 committed === null ||
248 committed.inputKind !== inputKind ||
249 (inputIsCollection && committed.inputCollection !== queryFnOrCollection) ||
250 dependenciesChanged
251 const pageShapeChanged =
252 committed === null ||
253 committed.pageSize !== pageSize ||
254 committed.initialPageParam !== initialPageParam
255 const needsNewController =
256 committed === null || needsNewCollection || pageShapeChanged
257
258 // Reuse the previous render's collection when every identity input matches,
259 // so a same-identity duplicate render shares its collection rather than
260 // starting a second sync of the source. An uncommitted collection has no
261 // subscriber, so GC can clean it up before a suspended update retries; a
262 // cleaned-up collection must be rebuilt, not reused.
263 const renderedComparison = compareLiveQueryWindowDependencies(
264 rendered?.dependencies,
265 identityDeps,
266 )
267 const canReuseRendered =
268 rendered !== null &&
269 rendered.collection.status !== `cleaned-up` &&
270 rendered.inputKind === inputKind &&
271 rendered.client === dbClient &&
272 rendered.pageSize === pageSize &&
273 rendered.initialPageParam === initialPageParam &&
274 (inputIsCollection
275 ? rendered.inputCollection === queryFnOrCollection
276 : usesLegacyDeps
277 ? !renderedComparison.changed
278 : renderedComparison.structurallyEqual)
279
280 let renderState = committed
281 if (needsNewController && canReuseRendered) {
282 // Built earlier this pre-commit render but not yet committed; reuse it.
283 renderState = rendered
284 } else if (needsNewController) {
285 let collection = committed?.collection
286 let warning: string | null = null
287
288 if (needsNewCollection) {
289 let inputValue = queryFnOrCollection
290 if (!inputIsCollection) {
291 if (preparedQueryValue === unpreparedQueryValue) {
292 preparedQueryValue = prepareQueryValue(
293 queryFnOrCollection,
294 dbClient,
295 deferredCollections,
296 )
297 }
298 inputValue = () => preparedQueryValue
299 }
300 const input = resolveLiveQueryWindowInput<TContext>(inputValue)
301 if (input.kind === `collection`) {
302 collection = input.collection
303 } else {
304 // Wrap the query with the first page's peek-ahead window; the controller
305 // grows the limit from here via setWindow.
306 collection = createLiveQueryCollection({
307 query: input.query.limit(pageSize + 1).offset(0),
308 // Match useLiveQuery: start sync during render so a synchronously
309 // loaded source is already published on the first commit, rather than
310 // flashing an empty idle commit. Renders that never commit are
311 // reclaimed by GC (gcTime), exactly as useLiveQuery relies on.
312 startSync: true,
313 gcTime: DEFAULT_GC_TIME_MS,
314 })
315 }
316 }
317
318 if (!collection) {
319 throw new Error(`useLiveInfiniteQuery: Failed to create a collection.`)
320 }
321
322 if (inputIsCollection) {
323 warning =
324 getLiveQueryWindowCollectionWarning(collection, pageSize + 1) ?? null
325 } else {
326 assertLiveQueryWindowManyResult(collection)
327 }
328
329 const canPreservePageCount = shouldPreserveLiveQueryWindowPageCount({
330 hasPreviousController: committed !== null,
331 previousInputKind: committed?.inputKind,
332 inputKind,
333 sameCollection:
334 inputIsCollection && committed?.inputCollection === collection,
335 dependenciesChanged,
336 dependenciesStructurallyEqual,
337 pageShapeChanged,
338 })
339 const previousPageCount = committed
340 ? Math.max(1, committed.controller.getSnapshot().pages.length)
341 : 1
342 const initialPageCount = canPreservePageCount ? previousPageCount : 1
343 renderState = {
344 inputKind,
345 inputCollection: inputIsCollection ? collection : null,
346 inputQuery: inputIsCollection ? null : queryFnOrCollection,
347 client: dbClient,
348 identityMode,
349 dependencies: inputIsCollection ? null : [...identityDeps],
350 pageSize,
351 initialPageParam,
352 collection,
353 controller: createLiveQueryWindowController(collection, {
354 pageSize,
355 initialPageParam,
356 initialPageCount,
357 }),
358 warning,
359 warned: false,
360 deferredCollections,
361 }
362 }
363 const currentRenderState = renderState!
364 const controller = currentRenderState.controller
365 // Record this render's state so a same-identity duplicate render reuses it.
366 // Committed state is recorded separately, at subscribe, so an abandoned
367 // render cannot overwrite the pages a committed render must preserve.
368 renderedRef.current = currentRenderState
369
370 const subscribe = useCallback(
371 (onStoreChange: () => void) => {
372 const unsubscribe = controller.subscribe(onStoreChange)
373 committedRef.current = currentRenderState
374 if (currentRenderState.warning && !currentRenderState.warned) {
375 currentRenderState.warned = true
376 console.warn(currentRenderState.warning)
377 }
378 for (const collection of currentRenderState.deferredCollections) {
379 collection._resumeSyncStart()
380 }
381 currentRenderState.deferredCollections.clear()
382 return unsubscribe
383 },
384 [controller, currentRenderState],
385 )
386 const getSnapshot = useCallback(() => controller.getSnapshot(), [controller])
387 const snapshot = useSyncExternalStore(subscribe, getSnapshot, getSnapshot)
388
389 const fetchNextPage = useCallback(
390 () => fetchNextLiveQueryWindowPage(controller),
391 [controller],
392 )
393
394 return {
395 data: snapshot.data as InferResultType<TContext>,
396 state: snapshot.state as EnabledLiveQueryReturn<TContext>[`state`],
397 status: snapshot.status as EnabledLiveQueryReturn<TContext>[`status`],
398 isLoading: snapshot.isLoading,
399 isReady: snapshot.isReady,
400 persistedStatus: snapshot.persistedStatus,
401 isPersistedReady: snapshot.isPersistedReady,
402 persistedError: snapshot.persistedError,
403 isIdle: snapshot.isIdle,
404 isError: snapshot.isError,
405 isCleanedUp: snapshot.isCleanedUp,
406 collection:
407 snapshot.collection as EnabledLiveQueryReturn<TContext>[`collection`],
408 isEnabled: snapshot.isEnabled,
409 pages: snapshot.pages as Array<Array<InferResultType<TContext>[number]>>,
410 pageParams: snapshot.pageParams as Array<number>,
411 fetchNextPage,
412 hasNextPage: snapshot.hasNextPage,
413 isFetchingNextPage: snapshot.isFetchingNextPage,
414 error: snapshot.error,
415 }
416}