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

useLiveInfiniteQuery.ts

332 lines11.4 KB

1'use client'
2​
3import { useCallback, useRef, useSyncExternalStore } from 'react'
4import {
5 bindLiveQueryWindow,
6 createLiveQuerySourceIdClaims,
7 fetchNextLiveQueryWindowPage,
8 getLiveQueryKey,
9 identifyLiveQuery,
10 isCollection,
11 readLiveQueryWindowPageShape,
12 rejectLiveQueryInput,
13 releaseDeferredOnReclaim,
14 resumeDeferredLiveQueryCollections,
15} from '@tanstack/db'
16import { useOptionalDbClient } from './DbProvider'
17import {
18 getIdentityScope,
19 prepareDerivedQuery,
20 prepareQueryValue,
21 warnDeprecatedDepsArray,
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 LiveQuerySourceIdClaims,
37 LiveQueryStatusFlags,
38 LiveQueryWindowBinding,
39 NonSingleResult,
40 QueryBuilder,
41} from '@tanstack/db'
42​
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
71​
72export type UseLiveInfiniteQueryReturnWithCollection<
73 TResult extends object,
74 TKey extends string | number,
75 TUtils extends Record<string, any>,
76> = LiveQueryStatusFlags & {
77 data: Array<TResult>
78 state: Map<TKey, TResult>
79 collection: Collection<TResult, TKey, TUtils> & NonSingleResult
80 status: CollectionStatus
81 isEnabled: true
82 pages: Array<Array<TResult>>
83 pageParams: Array<number>
84 fetchNextPage: () => Promise<void>
85 hasNextPage: boolean
86 isFetchingNextPage: boolean
88​
89type EnabledLiveQueryReturn<TContext extends Context> = ReturnType<
90 typeof useLiveQuery<TContext>
92​
93/** One render's window binding and what its commit still owes. */
94type InfiniteQueryRender = {
95 binding: LiveQueryWindowBinding
96 /** The query callback whose identity this render derived, if any. */
97 derivedQuery: unknown
98 deferredCollections: Set<
99 CollectionImplType<any, string | number, any, any, any>
100 >
101 /** Drops the reclaim release when this render commits. */
102 cancelReclaimRelease: (() => void) | undefined
103 warned: boolean
105​
106/**
107 * Create an infinite query using a query function with live updates.
108 *
109 * Uses `utils.setWindow()` to dynamically adjust the limit/offset window
110 * without recreating the live query collection on each page change.
111 *
112 * @param queryFn - Query function that defines what data to fetch. Must include `.orderBy()` for setWindow to work.
113 * @param config - Configuration including pageSize and an optional initial page label
114 * @param deps - Deprecated array of dependencies that trigger query re-execution when changed
115 * @returns Object with pages, data, and pagination controls
116 */
117​
118// Overload for pre-created collection (non-single result)
119export function useLiveInfiniteQuery<
120 TResult extends object,
121 TKey extends string | number,
122 TUtils extends Record<string, any>,
123>(
124 liveQueryCollection: Collection<TResult, TKey, TUtils> & NonSingleResult,
125 config: UseLiveInfiniteQueryConfig<any>,
126): UseLiveInfiniteQueryReturnWithCollection<TResult, TKey, TUtils>
127​
128// Overload for query function
129export function useLiveInfiniteQuery<TContext extends Context>(
130 queryFn: (q: InitialQueryBuilder) => QueryBuilder<TContext>,
131 config: UseLiveInfiniteQueryConfig<TContext>,
132 deps?: Array<unknown>,
133): UseLiveInfiniteQueryReturn<TContext>
134​
135// Implementation
136export function useLiveInfiniteQuery<TContext extends Context>(
137 queryFnOrCollection: any,
138 config: UseLiveInfiniteQueryConfig<TContext>,
139 deps?: Array<unknown>,
140): UseLiveInfiniteQueryReturn<TContext> {
141 const pageShape = readLiveQueryWindowPageShape(config)
142 const contextDbClient = useOptionalDbClient()
143 const dbClient = config.client ?? contextDbClient
144 const inputIsCollection = isCollection(queryFnOrCollection)
145​
146 const committedRef = useRef<InfiniteQueryRender | null>(null)
147 const committed = committedRef.current
148 // Like useLiveQuery's instance memo, keep the latest render whose binding
149 // built a window collection. A second render before commit, such as a
150 // StrictMode double render, reuses that collection instead of starting
151 // another. Each render still builds its own controller and page count from
152 // the committed binding, which an uncommitted render never changes.
153 const renderedRef = useRef<InfiniteQueryRender | null>(null)
154 const sourceIdsRef = useRef<LiveQuerySourceIdClaims | null>(null)
155 const derivedIdentityProfilerRef = useRef<DerivedIdentityProfiler>({
156 renderCount: 0,
157 totalMs: 0,
158 maxMs: 0,
159 warned: false,
160 })
161 const deferredCollections = new Set<
162 CollectionImplType<any, string | number, any, any, any>
163 >()
164 const identityScope = () =>
165 getIdentityScope(
166 (sourceIdsRef.current ??= createLiveQuerySourceIdClaims()),
167 dbClient,
168 `useLiveInfiniteQuery`,
169 )
170​
171 const queryKey = getLiveQueryKey(config)
172 const usesLegacyDeps =
173 !inputIsCollection && queryKey === undefined && deps !== undefined
174 let preparedQueryValue: unknown | typeof unpreparedQueryValue =
175 unpreparedQueryValue
176 let dependencies: ReadonlyArray<unknown> | undefined
177 let derivedQuery: unknown = undefined
178​
179 const rendered = renderedRef.current
180 let binding: LiveQueryWindowBinding
181 // The render boundary: a render that throws anywhere after preparation,
182 // such as an unhashable, single-result, or uncompilable query, never
183 // commits, so it releases the sync starts it deferred here.
184 try {
185 if (!inputIsCollection) {
186 if (queryKey !== undefined) {
187 dependencies = queryKey
188 } else if (usesLegacyDeps) {
189 dependencies = deps
190 warnDeprecatedDepsArray(`useLiveInfiniteQuery`)
191 } else if (
192 committed !== null &&
193 committed.derivedQuery === queryFnOrCollection &&
194 committed.binding.scope === dbClient
195 ) {
196 // The same callback in the same client scope keeps its identity.
197 derivedQuery = queryFnOrCollection
198 dependencies = committed.binding.dependencies
199 } else {
200 const preparation = prepareDerivedQuery(
201 queryFnOrCollection,
202 derivedIdentityProfilerRef.current,
203 identityScope(),
204 deferredCollections,
205 )
206 preparedQueryValue = preparation.value
207 derivedQuery = queryFnOrCollection
208 dependencies = preparation.identityDeps
209 }
210 }
211​
212 // The binding calls this only when it compiles a new window collection.
213 const compileQuery = () => {
214 if (preparedQueryValue === unpreparedQueryValue) {
215 preparedQueryValue = prepareQueryValue(
216 queryFnOrCollection,
217 dbClient,
218 deferredCollections,
219 )
220 if (usesLegacyDeps) {
221 // A dependency list decides reuse, so check the query when it
222 // compiles: it needs a stable identity and keeps its sources' IDs.
223 identifyLiveQuery(preparedQueryValue, identityScope())
224 }
225 }
226 return preparedQueryValue
227 }
228​
229 binding = bindLiveQueryWindow(
230 committed?.binding ?? null,
231 {
232 ...pageShape,
233 input:
234 typeof queryFnOrCollection === `function`
235 ? compileQuery
236 : queryFnOrCollection,
237 dependencies,
238 scope: dbClient,
239 client: dbClient,
240 queryKey,
241 recompile: usesLegacyDeps ? `dependencies` : `identity`,
242 },
243 rendered?.binding,
244 )
245 } catch (error) {
246 rejectLiveQueryInput(deferredCollections, error)
247 }
248​
249 let currentRenderState = committed
250 if (binding !== committed?.binding) {
251 const newCollection = binding.collection !== committed?.binding.collection
252 if (newCollection && binding.collection === rendered?.binding.collection) {
253 // Sources the earlier render deferred still resume at this commit.
254 for (const deferred of rendered.deferredCollections) {
255 deferredCollections.add(deferred)
256 }
257 }
258 const reusesRendered =
259 newCollection && binding.collection === rendered?.binding.collection
260 currentRenderState = {
261 binding,
262 derivedQuery,
263 deferredCollections,
264 // A render that never commits releases its deferred sync starts when
265 // garbage collection reclaims the window collection it built. A reused
266 // collection keeps the release its first render registered.
267 cancelReclaimRelease: reusesRendered
268 ? rendered.cancelReclaimRelease
269 : newCollection && binding.ownsCollection
270 ? releaseDeferredOnReclaim(binding.collection, deferredCollections)
271 : undefined,
272 warned: false,
273 }
274 // Keep a created collection for the next render only once it validated
275 // and started, so a retry after a startup error builds a new one.
276 if (binding.supplied) renderedRef.current = null
277 else if (newCollection && binding.ownsCollection) {
278 renderedRef.current = currentRenderState
279 }
280 }
281 const renderState = currentRenderState!
282 const controller = renderState.binding.controller
283​
284 const subscribe = useCallback(
285 (onStoreChange: () => void) => {
286 const unsubscribe = controller.subscribe(onStoreChange)
287 committedRef.current = renderState
288 if (renderState.binding.warning && !renderState.warned) {
289 renderState.warned = true
290 console.warn(renderState.binding.warning)
291 }
292 // A commit releases the starts itself, so it drops the reclaim release.
293 renderState.cancelReclaimRelease?.()
294 resumeDeferredLiveQueryCollections(renderState.deferredCollections)
295 return unsubscribe
296 },
297 [controller, renderState],
298 )
299 const getSnapshot = useCallback(() => controller.getSnapshot(), [controller])
300 const snapshot = useSyncExternalStore(subscribe, getSnapshot, () =>
301 controller.getServerSnapshot(),
302 )
303​
304 const fetchNextPage = useCallback(
305 () => fetchNextLiveQueryWindowPage(controller),
306 [controller],
307 )
308​
309 return {
310 data: snapshot.data as InferResultType<TContext>,
311 get state() {
312 return snapshot.state as EnabledLiveQueryReturn<TContext>[`state`]
313 },
314 status: snapshot.status as EnabledLiveQueryReturn<TContext>[`status`],
315 isLoading: snapshot.isLoading,
316 isReady: snapshot.isReady,
317 isIdle: snapshot.isIdle,
318 isLoadingError: snapshot.isLoadingError,
319 isCrashed: snapshot.isCrashed,
320 isCleanedUp: snapshot.isCleanedUp,
321 isSyncError: snapshot.isSyncError,
322 collection:
323 snapshot.collection as EnabledLiveQueryReturn<TContext>[`collection`],
324 isEnabled: snapshot.isEnabled,
325 pages: snapshot.pages as Array<Array<InferResultType<TContext>[number]>>,
326 pageParams: snapshot.pageParams as Array<number>,
327 fetchNextPage,
328 hasNextPage: snapshot.hasNextPage,
329 isFetchingNextPage: snapshot.isFetchingNextPage,
330 health: snapshot.health,
331 }