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