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

useLiveInfiniteQuery.ts

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