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

useLiveInfiniteQuery.ts

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