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

useLiveInfiniteQuery.ts

413 lines14.2 KB

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
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
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
99​
100type EnabledLiveQueryReturn<TContext extends Context> = ReturnType<
101 typeof useLiveQuery<TContext>
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 >
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.
261 const renderedComparison = compareLiveQueryWindowDependencies(
262 rendered?.dependencies,
263 identityDeps,
264 )
265 const canReuseRendered =
266 rendered !== null &&
267 rendered.inputKind === inputKind &&
268 rendered.client === dbClient &&
269 rendered.pageSize === pageSize &&
270 rendered.initialPageParam === initialPageParam &&
271 (inputIsCollection
272 ? rendered.inputCollection === queryFnOrCollection
273 : usesLegacyDeps
274 ? !renderedComparison.changed
275 : renderedComparison.structurallyEqual)
276​
277 let renderState = committed
278 if (needsNewController && canReuseRendered) {
279 // Built earlier this pre-commit render but not yet committed; reuse it.
280 renderState = rendered
281 } else if (needsNewController) {
282 let collection = committed?.collection
283 let warning: string | null = null
284​
285 if (needsNewCollection) {
286 let inputValue = queryFnOrCollection
287 if (!inputIsCollection) {
288 if (preparedQueryValue === unpreparedQueryValue) {
289 preparedQueryValue = prepareQueryValue(
290 queryFnOrCollection,
291 dbClient,
292 deferredCollections,
293 )
294 }
295 inputValue = () => preparedQueryValue
296 }
297 const input = resolveLiveQueryWindowInput<TContext>(inputValue)
298 if (input.kind === `collection`) {
299 collection = input.collection
300 } else {
301 // Wrap the query with the first page's peek-ahead window; the controller
302 // grows the limit from here via setWindow.
303 collection = createLiveQueryCollection({
304 query: input.query.limit(pageSize + 1).offset(0),
305 // Match useLiveQuery: start sync during render so a synchronously
306 // loaded source is already published on the first commit, rather than
307 // flashing an empty idle commit. Renders that never commit are
308 // reclaimed by GC (gcTime), exactly as useLiveQuery relies on.
309 startSync: true,
310 gcTime: DEFAULT_GC_TIME_MS,
311 })
312 }
313 }
314​
315 if (!collection) {
316 throw new Error(`useLiveInfiniteQuery: Failed to create a collection.`)
317 }
318​
319 if (inputIsCollection) {
320 warning =
321 getLiveQueryWindowCollectionWarning(collection, pageSize + 1) ?? null
322 } else {
323 assertLiveQueryWindowManyResult(collection)
324 }
325​
326 const canPreservePageCount = shouldPreserveLiveQueryWindowPageCount({
327 hasPreviousController: committed !== null,
328 previousInputKind: committed?.inputKind,
329 inputKind,
330 sameCollection:
331 inputIsCollection && committed?.inputCollection === collection,
332 dependenciesChanged,
333 dependenciesStructurallyEqual,
334 pageShapeChanged,
335 })
336 const previousPageCount = committed
337 ? Math.max(1, committed.controller.getSnapshot().pages.length)
338 : 1
339 const initialPageCount = canPreservePageCount ? previousPageCount : 1
340 renderState = {
341 inputKind,
342 inputCollection: inputIsCollection ? collection : null,
343 inputQuery: inputIsCollection ? null : queryFnOrCollection,
344 client: dbClient,
345 identityMode,
346 dependencies: inputIsCollection ? null : [...identityDeps],
347 pageSize,
348 initialPageParam,
349 collection,
350 controller: createLiveQueryWindowController(collection, {
351 pageSize,
352 initialPageParam,
353 initialPageCount,
354 }),
355 warning,
356 warned: false,
357 deferredCollections,
358 }
359 }
360 const currentRenderState = renderState!
361 const controller = currentRenderState.controller
362 // Record this render's state so a same-identity duplicate render reuses it.
363 // Committed state is recorded separately, at subscribe, so an abandoned
364 // render cannot overwrite the pages a committed render must preserve.
365 renderedRef.current = currentRenderState
366​
367 const subscribe = useCallback(
368 (onStoreChange: () => void) => {
369 const unsubscribe = controller.subscribe(onStoreChange)
370 committedRef.current = currentRenderState
371 if (currentRenderState.warning && !currentRenderState.warned) {
372 currentRenderState.warned = true
373 console.warn(currentRenderState.warning)
374 }
375 for (const collection of currentRenderState.deferredCollections) {
376 collection._resumeSyncStart()
377 }
378 currentRenderState.deferredCollections.clear()
379 return unsubscribe
380 },
381 [controller, currentRenderState],
382 )
383 const getSnapshot = useCallback(() => controller.getSnapshot(), [controller])
384 const snapshot = useSyncExternalStore(subscribe, getSnapshot, getSnapshot)
385​
386 const fetchNextPage = useCallback(
387 () => fetchNextLiveQueryWindowPage(controller),
388 [controller],
389 )
390​
391 return {
392 data: snapshot.data as InferResultType<TContext>,
393 state: snapshot.state as EnabledLiveQueryReturn<TContext>[`state`],
394 status: snapshot.status as EnabledLiveQueryReturn<TContext>[`status`],
395 isLoading: snapshot.isLoading,
396 isReady: snapshot.isReady,
397 persistedStatus: snapshot.persistedStatus,
398 isPersistedReady: snapshot.isPersistedReady,
399 persistedError: snapshot.persistedError,
400 isIdle: snapshot.isIdle,
401 isError: snapshot.isError,
402 isCleanedUp: snapshot.isCleanedUp,
403 collection:
404 snapshot.collection as EnabledLiveQueryReturn<TContext>[`collection`],
405 isEnabled: snapshot.isEnabled,
406 pages: snapshot.pages as Array<Array<InferResultType<TContext>[number]>>,
407 pageParams: snapshot.pageParams as Array<number>,
408 fetchNextPage,
409 hasNextPage: snapshot.hasNextPage,
410 isFetchingNextPage: snapshot.isFetchingNextPage,
411 error: snapshot.error,
412 }