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