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

useLiveInfiniteQuery.ts

395 lines13.3 KB

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