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

useLiveInfiniteQuery.ts

317 lines10.7 KB

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