Open History to see the last commit
1import { useCallback, useEffect, useMemo, useRef, useState } from 'react'
2import { CollectionImpl } from '@tanstack/db'
3import { useLiveQuery } from './useLiveQuery'
4import type {
5 Collection,
6 Context,
7 InferResultType,
8 InitialQueryBuilder,
9 LiveQueryCollectionUtils,
10 NonSingleResult,
11 QueryBuilder,
12} from '@tanstack/db'
13
14/**
15 * Type guard to check if utils object has setWindow method (LiveQueryCollectionUtils)
16 */
17function isLiveQueryCollectionUtils(
18 utils: unknown,
19): utils is LiveQueryCollectionUtils {
20 return typeof (utils as any).setWindow === `function`
21}
22
23export type UseLiveInfiniteQueryConfig<TContext extends Context> = {
24 pageSize?: number
25 initialPageParam?: number
26 /**
27 * @deprecated This callback is not used by the current implementation.
28 * Pagination is determined internally via a peek-ahead strategy.
29 * Provided for API compatibility with TanStack Query conventions.
30 */
31 getNextPageParam?: (
32 lastPage: Array<InferResultType<TContext>[number]>,
33 allPages: Array<Array<InferResultType<TContext>[number]>>,
34 lastPageParam: number,
35 allPageParams: Array<number>,
36 ) => number | undefined
37}
38
39export type UseLiveInfiniteQueryReturn<TContext extends Context> = Omit<
40 ReturnType<typeof useLiveQuery<TContext>>,
41 `data`
42> & {
43 data: InferResultType<TContext>
44 pages: Array<Array<InferResultType<TContext>[number]>>
45 pageParams: Array<number>
46 fetchNextPage: () => void
47 hasNextPage: boolean
48 isFetchingNextPage: boolean
49}
50
51/**
52 * Create an infinite query using a query function with live updates
53 *
54 * Uses `utils.setWindow()` to dynamically adjust the limit/offset window
55 * without recreating the live query collection on each page change.
56 *
57 * @param queryFn - Query function that defines what data to fetch. Must include `.orderBy()` for setWindow to work.
58 * @param config - Configuration including pageSize and getNextPageParam
59 * @param deps - Array of dependencies that trigger query re-execution when changed
60 * @returns Object with pages, data, and pagination controls
61 *
62 * @example
63 * // Basic infinite query
64 * const { data, pages, fetchNextPage, hasNextPage } = useLiveInfiniteQuery(
65 * (q) => q
66 * .from({ posts: postsCollection })
67 * .orderBy(({ posts }) => posts.createdAt, 'desc')
68 * .select(({ posts }) => ({
69 * id: posts.id,
70 * title: posts.title
71 * })),
72 * {
73 * pageSize: 20,
74 * getNextPageParam: (lastPage, allPages) =>
75 * lastPage.length === 20 ? allPages.length : undefined
76 * }
77 * )
78 *
79 * @example
80 * // With dependencies
81 * const { pages, fetchNextPage } = useLiveInfiniteQuery(
82 * (q) => q
83 * .from({ posts: postsCollection })
84 * .where(({ posts }) => eq(posts.category, category))
85 * .orderBy(({ posts }) => posts.createdAt, 'desc'),
86 * {
87 * pageSize: 10,
88 * getNextPageParam: (lastPage) =>
89 * lastPage.length === 10 ? lastPage.length : undefined
90 * },
91 * [category]
92 * )
93 *
94 * @example
95 * // Router loader pattern with pre-created collection
96 * // In loader:
97 * const postsQuery = createLiveQueryCollection({
98 * query: (q) => q
99 * .from({ posts: postsCollection })
100 * .orderBy(({ posts }) => posts.createdAt, 'desc')
101 * .limit(20)
102 * })
103 * await postsQuery.preload()
104 * return { postsQuery }
105 *
106 * // In component:
107 * const { postsQuery } = useLoaderData()
108 * const { data, fetchNextPage, hasNextPage } = useLiveInfiniteQuery(
109 * postsQuery,
110 * {
111 * pageSize: 20,
112 * getNextPageParam: (lastPage) => lastPage.length === 20 ? lastPage.length : undefined
113 * }
114 * )
115 */
116
117// Overload for pre-created collection (non-single result)
118export function useLiveInfiniteQuery<
119 TResult extends object,
120 TKey extends string | number,
121 TUtils extends Record<string, any>,
122>(
123 liveQueryCollection: Collection<TResult, TKey, TUtils> & NonSingleResult,
124 config: UseLiveInfiniteQueryConfig<any>,
125): UseLiveInfiniteQueryReturn<any>
126
127// Overload for query function
128export function useLiveInfiniteQuery<TContext extends Context>(
129 queryFn: (q: InitialQueryBuilder) => QueryBuilder<TContext>,
130 config: UseLiveInfiniteQueryConfig<TContext>,
131 deps?: Array<unknown>,
132): UseLiveInfiniteQueryReturn<TContext>
133
134// Implementation
135export function useLiveInfiniteQuery<TContext extends Context>(
136 queryFnOrCollection: any,
137 config: UseLiveInfiniteQueryConfig<TContext>,
138 deps: Array<unknown> = [],
139): UseLiveInfiniteQueryReturn<TContext> {
140 const pageSize = config.pageSize || 20
141 const initialPageParam = config.initialPageParam ?? 0
142
143 // Detect if input is a collection or query function
144 const isCollection = queryFnOrCollection instanceof CollectionImpl
145
146 // Validate input type
147 if (!isCollection && typeof queryFnOrCollection !== `function`) {
148 throw new Error(
149 `useLiveInfiniteQuery: First argument must be either a pre-created live query collection (CollectionImpl) ` +
150 `or a query function. Received: ${typeof queryFnOrCollection}`,
151 )
152 }
153
154 // Track how many pages have been loaded
155 const [loadedPageCount, setLoadedPageCount] = useState(1)
156 const [isFetchingNextPage, setIsFetchingNextPage] = useState(false)
157
158 // Track collection instance and whether we've validated it (only for pre-created collections)
159 const collectionRef = useRef(isCollection ? queryFnOrCollection : null)
160 const hasValidatedCollectionRef = useRef(false)
161
162 // Track deps for query functions (stringify for comparison)
163 let depsKey: string
164 try {
165 depsKey = JSON.stringify(deps)
166 } catch {
167 throw new Error(
168 `useLiveInfiniteQuery: dependency array contains values that cannot be serialized (e.g. circular references). ` +
169 `Ensure all dependency values are JSON-serializable.`,
170 )
171 }
172 const prevDepsKeyRef = useRef(depsKey)
173
174 // Reset pagination when inputs change
175 useEffect(() => {
176 let shouldReset = false
177
178 if (isCollection) {
179 // Reset if collection instance changed
180 if (collectionRef.current !== queryFnOrCollection) {
181 collectionRef.current = queryFnOrCollection
182 hasValidatedCollectionRef.current = false
183 shouldReset = true
184 }
185 } else {
186 // Reset if deps changed (for query functions)
187 if (prevDepsKeyRef.current !== depsKey) {
188 prevDepsKeyRef.current = depsKey
189 shouldReset = true
190 }
191 }
192
193 if (shouldReset) {
194 setLoadedPageCount(1)
195 }
196 }, [isCollection, queryFnOrCollection, depsKey])
197
198 // Create a live query without limit/offset — setWindow() is the sole authority
199 // Either pass collection directly or wrap query function
200 const queryResult = isCollection
201 ? useLiveQuery(queryFnOrCollection)
202 : useLiveQuery((q) => queryFnOrCollection(q), deps)
203
204 // Adjust window when pagination changes
205 useEffect(() => {
206 const utils = queryResult.collection.utils
207 const expectedOffset = 0
208 const expectedLimit = loadedPageCount * pageSize + 1 // +1 for peek ahead
209
210 // Check if collection has orderBy (required for setWindow)
211 if (!isLiveQueryCollectionUtils(utils)) {
212 // For pre-created collections, throw an error if no orderBy
213 if (isCollection) {
214 throw new Error(
215 `useLiveInfiniteQuery: Pre-created live query collection must have an orderBy clause for infinite pagination to work. ` +
216 `Please add .orderBy() to your createLiveQueryCollection query.`,
217 )
218 }
219 return
220 }
221
222 // For pre-created collections, validate window on first check
223 if (isCollection && !hasValidatedCollectionRef.current) {
224 const currentWindow = utils.getWindow()
225 if (
226 currentWindow &&
227 (currentWindow.offset !== expectedOffset ||
228 currentWindow.limit !== expectedLimit)
229 ) {
230 console.warn(
231 `useLiveInfiniteQuery: Pre-created collection has window {offset: ${currentWindow.offset}, limit: ${currentWindow.limit}} ` +
232 `but hook expects {offset: ${expectedOffset}, limit: ${expectedLimit}}. Adjusting window now.`,
233 )
234 }
235 hasValidatedCollectionRef.current = true
236 }
237
238 // For query functions, wait until collection is ready
239 if (!isCollection && !queryResult.isReady) return
240
241 // Adjust the window
242 let cancelled = false
243 const result = utils.setWindow({
244 offset: expectedOffset,
245 limit: expectedLimit,
246 })
247
248 if (result !== true) {
249 setIsFetchingNextPage(true)
250 result
251 .catch((error: unknown) => {
252 if (!cancelled)
253 console.error(`useLiveInfiniteQuery: setWindow failed:`, error)
254 })
255 .finally(() => {
256 if (!cancelled) setIsFetchingNextPage(false)
257 })
258 } else {
259 setIsFetchingNextPage(false)
260 }
261
262 return () => {
263 cancelled = true
264 }
265 }, [
266 isCollection,
267 queryResult.collection,
268 queryResult.isReady,
269 loadedPageCount,
270 pageSize,
271 ])
272
273 // Split the data array into pages and determine if there's a next page
274 const { pages, pageParams, hasNextPage, flatData } = useMemo(() => {
275 const dataArray = (
276 Array.isArray(queryResult.data) ? queryResult.data : []
277 ) as InferResultType<TContext>
278 const totalItemsRequested = loadedPageCount * pageSize
279
280 // Check if we have more data than requested (the peek ahead item)
281 const hasMore = dataArray.length > totalItemsRequested
282
283 // Build pages array (without the peek ahead item)
284 const pagesResult: Array<Array<InferResultType<TContext>[number]>> = []
285 const pageParamsResult: Array<number> = []
286
287 for (let i = 0; i < loadedPageCount; i++) {
288 const pageData = dataArray.slice(i * pageSize, (i + 1) * pageSize)
289 pagesResult.push(pageData)
290 pageParamsResult.push(initialPageParam + i)
291 }
292
293 // Flatten the pages for the data return (without peek ahead item)
294 const flatDataResult = dataArray.slice(
295 0,
296 totalItemsRequested,
297 ) as InferResultType<TContext>
298
299 return {
300 pages: pagesResult,
301 pageParams: pageParamsResult,
302 hasNextPage: hasMore,
303 flatData: flatDataResult,
304 }
305 }, [queryResult.data, loadedPageCount, pageSize, initialPageParam])
306
307 // Fetch next page
308 const fetchNextPage = useCallback(() => {
309 if (!hasNextPage || isFetchingNextPage) return
310
311 setLoadedPageCount((prev) => prev + 1)
312 }, [hasNextPage, isFetchingNextPage])
313
314 return {
315 ...queryResult,
316 data: flatData,
317 pages,
318 pageParams,
319 fetchNextPage,
320 hasNextPage,
321 isFetchingNextPage,
322 } as UseLiveInfiniteQueryReturn<TContext>
323}