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

useLiveInfiniteQuery.ts

378 lines12.5 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 const inputKind = inputIsCollection ? `collection` : `query`
173 const derivedIdentityProfilerRef = useRef<DerivedIdentityProfiler>({
174 renderCount: 0,
175 totalMs: 0,
176 maxMs: 0,
177 warned: false,
178 })
179 const legacyUnhashableIdentityRef = useRef<Array<unknown>>([
180 `legacy-unhashable`,
181 ])
182 const deferredCollections = new Set<
183 CollectionImplType<any, string | number, any, any, any>
184 >()
185​
186 let preparedQueryValue: unknown | typeof unpreparedQueryValue =
187 unpreparedQueryValue
188 let identityDeps: ReadonlyArray<unknown> = []
189 let identityMode: InfiniteQueryRenderState[`identityMode`] = `collection`
190​
191 if (!inputIsCollection) {
192 if (config.queryKey !== undefined) {
193 identityMode = `queryKey`
194 identityDeps = config.queryKey
195 } else if (deps !== undefined) {
196 identityMode = `legacyDeps`
197 identityDeps = deps
198 warnDeprecatedDepsArray(`useLiveInfiniteQuery`)
199 } else if (
200 committed?.identityMode === `derived` &&
201 committed.inputQuery === queryFnOrCollection &&
202 committed.client === dbClient
203 ) {
204 identityMode = `derived`
205 identityDeps = committed.dependencies ?? []
206 } else {
207 identityMode = `derived`
208 const preparation = prepareDerivedQuery(
209 queryFnOrCollection,
210 dbClient,
211 derivedIdentityProfilerRef.current,
212 deferredCollections,
213 )
214 preparedQueryValue = preparation.value
215 if (preparation.status === `hashable`) {
216 identityDeps = preparation.identityDeps
217 } else {
218 warnUnhashableDerivedIdentity(preparation.error)
219 identityDeps = legacyUnhashableIdentityRef.current
220 }
221 }
222 }
223​
224 const usesLegacyDeps =
225 !inputIsCollection && config.queryKey === undefined && deps !== undefined
226 const dependencyComparison = compareLiveQueryWindowDependencies(
227 committed?.dependencies,
228 identityDeps,
229 )
230 const sameClient = committed?.client === dbClient
231 const dependenciesChanged =
232 !inputIsCollection &&
233 (!sameClient ||
234 (usesLegacyDeps
235 ? dependencyComparison.changed
236 : !dependencyComparison.structurallyEqual))
237 const dependenciesStructurallyEqual =
238 usesLegacyDeps && sameClient && dependencyComparison.structurallyEqual
239 const needsNewCollection =
240 committed === null ||
241 committed.inputKind !== inputKind ||
242 (inputIsCollection && committed.inputCollection !== queryFnOrCollection) ||
243 dependenciesChanged
244 const pageShapeChanged =
245 committed === null ||
246 committed.pageSize !== pageSize ||
247 committed.initialPageParam !== initialPageParam
248 const needsNewController =
249 committed === null || needsNewCollection || pageShapeChanged
250​
251 let renderState = committed
252 if (needsNewController) {
253 let collection = committed?.collection
254 let warning: string | null = null
255​
256 if (needsNewCollection) {
257 let inputValue = queryFnOrCollection
258 if (!inputIsCollection) {
259 if (preparedQueryValue === unpreparedQueryValue) {
260 preparedQueryValue = prepareQueryValue(
261 queryFnOrCollection,
262 dbClient,
263 deferredCollections,
264 )
265 }
266 inputValue = () => preparedQueryValue
267 }
268 const input = resolveLiveQueryWindowInput<TContext>(inputValue)
269 if (input.kind === `collection`) {
270 collection = input.collection
271 } else {
272 // Wrap the query with the first page's peek-ahead window; the controller
273 // grows the limit from here via setWindow.
274 collection = createLiveQueryCollection({
275 query: input.query.limit(pageSize + 1).offset(0),
276 // Construction happens during render. Synchronization starts only when
277 // useSyncExternalStore commits the controller subscription.
278 startSync: false,
279 gcTime: DEFAULT_GC_TIME_MS,
280 })
281 }
282 }
283​
284 if (!collection) {
285 throw new Error(`useLiveInfiniteQuery: Failed to create a collection.`)
286 }
287​
288 if (inputIsCollection) {
289 warning =
290 getLiveQueryWindowCollectionWarning(collection, pageSize + 1) ?? null
291 } else {
292 assertLiveQueryWindowManyResult(collection)
293 }
294​
295 const canPreservePageCount = shouldPreserveLiveQueryWindowPageCount({
296 hasPreviousController: committed !== null,
297 previousInputKind: committed?.inputKind,
298 inputKind,
299 sameCollection:
300 inputIsCollection && committed?.inputCollection === collection,
301 dependenciesChanged,
302 dependenciesStructurallyEqual,
303 pageShapeChanged,
304 })
305 const previousPageCount = committed
306 ? Math.max(1, committed.controller.getSnapshot().pages.length)
307 : 1
308 const initialPageCount = canPreservePageCount ? previousPageCount : 1
309 renderState = {
310 inputKind,
311 inputCollection: inputIsCollection ? collection : null,
312 inputQuery: inputIsCollection ? null : queryFnOrCollection,
313 client: dbClient,
314 identityMode,
315 dependencies: inputIsCollection ? null : [...identityDeps],
316 pageSize,
317 initialPageParam,
318 collection,
319 controller: createLiveQueryWindowController(collection, {
320 pageSize,
321 initialPageParam,
322 initialPageCount,
323 }),
324 warning,
325 warned: false,
326 deferredCollections,
327 }
328 }
329 const currentRenderState = renderState!
330 const controller = currentRenderState.controller
331​
332 const subscribe = useCallback(
333 (onStoreChange: () => void) => {
334 const unsubscribe = controller.subscribe(onStoreChange)
335 committedRef.current = currentRenderState
336 if (currentRenderState.warning && !currentRenderState.warned) {
337 currentRenderState.warned = true
338 console.warn(currentRenderState.warning)
339 }
340 for (const collection of currentRenderState.deferredCollections) {
341 collection._resumeSyncStart()
342 }
343 currentRenderState.deferredCollections.clear()
344 return unsubscribe
345 },
346 [controller, currentRenderState],
347 )
348 const getSnapshot = useCallback(() => controller.getSnapshot(), [controller])
349 const snapshot = useSyncExternalStore(subscribe, getSnapshot, getSnapshot)
350​
351 const fetchNextPage = useCallback(
352 () => fetchNextLiveQueryWindowPage(controller),
353 [controller],
354 )
355​
356 return {
357 data: snapshot.data as InferResultType<TContext>,
358 state: snapshot.state as EnabledLiveQueryReturn<TContext>[`state`],
359 status: snapshot.status as EnabledLiveQueryReturn<TContext>[`status`],
360 isLoading: snapshot.isLoading,
361 isReady: snapshot.isReady,
362 persistedStatus: snapshot.persistedStatus,
363 isPersistedReady: snapshot.isPersistedReady,
364 persistedError: snapshot.persistedError,
365 isIdle: snapshot.isIdle,
366 isError: snapshot.isError,
367 isCleanedUp: snapshot.isCleanedUp,
368 collection:
369 snapshot.collection as EnabledLiveQueryReturn<TContext>[`collection`],
370 isEnabled: snapshot.isEnabled,
371 pages: snapshot.pages as Array<Array<InferResultType<TContext>[number]>>,
372 pageParams: snapshot.pageParams as Array<number>,
373 fetchNextPage,
374 hasNextPage: snapshot.hasNextPage,
375 isFetchingNextPage: snapshot.isFetchingNextPage,
376 error: snapshot.error,
377 }