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

useLiveInfiniteQuery.ts

382 lines12.8 KB

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