Open History to see the last commit
1import { QueryObserver } from './queryObserver'
2import { hasNextPage, hasPreviousPage } from './infiniteQueryBehavior'
3import type { Subscribable } from './subscribable'
4import type {
5 DefaultError,
6 DefaultedInfiniteQueryObserverOptionsBase,
7 DefaultedQueryObserverOptions,
8 FetchPageDirectionMode,
9 InfiniteData,
10 InfiniteQueryFetchNextPageArgs,
11 InfiniteQueryFetchPreviousPageArgs,
12 InfiniteQueryObserverOptions,
13 InfiniteQueryObserverOptionsBase,
14 InfiniteQueryObserverResult,
15 QueryKey,
16 QueryObserverOptions,
17} from './types'
18import type { QueryClient } from './queryClient'
19import type { Query } from './query'
20β
21type InfiniteQueryObserverListener<
22 TData,
23 TError,
24 TPageParam,
25 TMode extends FetchPageDirectionMode,
26> = (
27 result: InfiniteQueryObserverResult<TData, TError, TPageParam, TMode>,
28) => void
29β
30/**
31 * An `InfiniteQueryObserver` extends `QueryObserver` to observe and switch
32 * between infinite queries. It augments the base `QueryObserverResult` with
33 * infinite-query-specific fields and methods, such as `hasNextPage` and
34 * `fetchNextPage`, and is the primitive that framework adapters (e.g.
35 * `useInfiniteQuery`) build their hooks on top of.
36 * @example
37 * ```ts
38 * const observer = new InfiniteQueryObserver(queryClient, {
39 * queryKey: ['projects'],
40 * queryFn: ({ pageParam }) => fetchProjects(pageParam),
41 * initialPageParam: 0,
42 * getNextPageParam: (lastPage) => lastPage.nextCursor,
43 * })
44 *
45 * const unsubscribe = observer.subscribe((result) => console.log(result))
46 * ```
47 */
48export class InfiniteQueryObserver<
49 TQueryFnData = unknown,
50 TError = DefaultError,
51 TData = InfiniteData<TQueryFnData>,
52 TQueryKey extends QueryKey = QueryKey,
53 TPageParam = unknown,
54 TMode extends FetchPageDirectionMode = undefined,
55> extends QueryObserver<
56 TQueryFnData,
57 TError,
58 TData,
59 InfiniteData<TQueryFnData, TPageParam>,
60 TQueryKey
61> {
62 // Type override
63 override subscribe!: Subscribable<
64 InfiniteQueryObserverListener<TData, TError, TPageParam, TMode>
65 >['subscribe']
66β
67 // Type override
68 override getCurrentResult!: ReplaceReturnType<
69 QueryObserver<
70 TQueryFnData,
71 TError,
72 TData,
73 InfiniteData<TQueryFnData, TPageParam>,
74 TQueryKey
75 >['getCurrentResult'],
76 InfiniteQueryObserverResult<TData, TError, TPageParam, TMode>
77 >
78β
79 // Type override
80 override trackResult!: ReplaceReturnType<
81 QueryObserver<
82 TQueryFnData,
83 TError,
84 TData,
85 InfiniteData<TQueryFnData, TPageParam>,
86 TQueryKey
87 >['trackResult'],
88 InfiniteQueryObserverResult<TData, TError, TPageParam, TMode>
89 >
90β
91 // Type override
92 override refetch!: ReplaceReturnType<
93 QueryObserver<
94 TQueryFnData,
95 TError,
96 TData,
97 InfiniteData<TQueryFnData, TPageParam>,
98 TQueryKey
99 >['refetch'],
100 Promise<InfiniteQueryObserverResult<TData, TError, TPageParam, TMode>>
101 >
102β
103 // Type override
104 protected override fetch!: ReplaceReturnType<
105 QueryObserver<
106 TQueryFnData,
107 TError,
108 TData,
109 InfiniteData<TQueryFnData, TPageParam>,
110 TQueryKey
111 >['fetch'],
112 Promise<InfiniteQueryObserverResult<TData, TError, TPageParam, TMode>>
113 >
114β
115 constructor(
116 client: QueryClient,
117 options: InfiniteQueryObserverOptionsBase<
118 TQueryFnData,
119 TError,
120 TData,
121 TQueryKey,
122 TPageParam,
123 undefined
124 > & { mode?: TMode },
125 )
126 constructor(
127 client: QueryClient,
128 options: InfiniteQueryObserverOptionsBase<
129 TQueryFnData,
130 TError,
131 TData,
132 TQueryKey,
133 TPageParam,
134 'manual'
135 > & { mode: TMode },
136 )
137 constructor(
138 client: QueryClient,
139 options: InfiniteQueryObserverOptions<
140 TQueryFnData,
141 TError,
142 TData,
143 TQueryKey,
144 TPageParam,
145 TMode
146 >,
147 )
148 constructor(
149 client: QueryClient,
150 options: InfiniteQueryObserverOptions<
151 TQueryFnData,
152 TError,
153 TData,
154 TQueryKey,
155 TPageParam
156 >,
157 ) {
158 super(client, options)
159 }
160β
161 protected override bindMethods(): void {
162 super.bindMethods()
163 this.fetchNextPage = this.fetchNextPage.bind(this)
164 this.fetchPreviousPage = this.fetchPreviousPage.bind(this)
165 }
166β
167 /**
168 * Updates the observer's options. Behaves the same as
169 * `QueryObserver.setOptions`, additionally marking the options as
170 * belonging to an infinite query before delegating to the base
171 * implementation.
172 * @param options - The new infinite query observer options.
173 */
174 override setOptions(
175 options: InfiniteQueryObserverOptionsBase<
176 TQueryFnData,
177 TError,
178 TData,
179 TQueryKey,
180 TPageParam,
181 TMode
182 >,
183 ): void
184 override setOptions(
185 options: QueryObserverOptions<
186 TQueryFnData,
187 TError,
188 TData,
189 InfiniteData<TQueryFnData, TPageParam>,
190 TQueryKey
191 >,
192 ): void
193 override setOptions(
194 options:
195 | QueryObserverOptions<
196 TQueryFnData,
197 TError,
198 TData,
199 InfiniteData<TQueryFnData, TPageParam>,
200 TQueryKey
201 >
202 | InfiniteQueryObserverOptionsBase<
203 TQueryFnData,
204 TError,
205 TData,
206 TQueryKey,
207 TPageParam,
208 TMode
209 >,
210 ): void {
211 options._type = 'infinite'
212 super.setOptions(options)
213 }
214β
215 /**
216 * The infinite-query counterpart of {@link QueryObserver#getOptimisticResult}, marking the
217 * options as an infinite query before delegating to it. Called by framework adapters (e.g.
218 * `useInfiniteQuery`) ahead of subscribing, to compute the current `InfiniteQueryObserverResult`
219 * synchronously.
220 * @param options - The defaulted infinite query observer options to compute the result for.
221 * @returns The result for the given options.
222 */
223 override getOptimisticResult(
224 options: DefaultedInfiniteQueryObserverOptionsBase<
225 TQueryFnData,
226 TError,
227 TData,
228 TQueryKey,
229 TPageParam,
230 TMode
231 >,
232 ): InfiniteQueryObserverResult<TData, TError, TPageParam, TMode>
233 override getOptimisticResult(
234 options: DefaultedQueryObserverOptions<
235 TQueryFnData,
236 TError,
237 TData,
238 InfiniteData<TQueryFnData, TPageParam>,
239 TQueryKey
240 >,
241 ): InfiniteQueryObserverResult<TData, TError, TPageParam, TMode>
242 override getOptimisticResult(
243 options:
244 | DefaultedQueryObserverOptions<
245 TQueryFnData,
246 TError,
247 TData,
248 InfiniteData<TQueryFnData, TPageParam>,
249 TQueryKey
250 >
251 | DefaultedInfiniteQueryObserverOptionsBase<
252 TQueryFnData,
253 TError,
254 TData,
255 TQueryKey,
256 TPageParam,
257 TMode
258 >,
259 ): InfiniteQueryObserverResult<TData, TError, TPageParam, TMode> {
260 options._type = 'infinite'
261 return super.getOptimisticResult(options) as InfiniteQueryObserverResult<
262 TData,
263 TError,
264 TPageParam,
265 TMode
266 >
267 }
268β
269 /**
270 * Fetches the next page of the infinite query and returns a promise that
271 * resolves with the resulting `InfiniteQueryObserverResult`. The page
272 * param used for the fetch is determined by `getNextPageParam`, which
273 * receives the current pages/page params and whose result also determines
274 * `hasNextPage`. In manual mode, pass the parameter in `args[0].pageParam`.
275 * @param args - Set `cancelRefetch` to `false` to ignore the call while a fetch is running,
276 * and `throwOnError` to `true` to reject when the fetch fails.
277 * @returns A promise that resolves with the result after the next page is fetched. With
278 * `cancelRefetch: false`, a running fetch is reused instead, so the next page may not be fetched.
279 * @see {@link InfiniteQueryObserver#fetchPreviousPage}
280 * @example
281 * ```ts
282 * const { hasNextPage } = observer.getCurrentResult()
283 *
284 * if (hasNextPage) {
285 * await observer.fetchNextPage()
286 * }
287 * ```
288 */
289 fetchNextPage(
290 ...args: InfiniteQueryFetchNextPageArgs<TPageParam, TMode>
291 ): Promise<InfiniteQueryObserverResult<TData, TError, TPageParam, TMode>> {
292 const { pageParam, ...options } = args[0] ?? ({} as any)
293 return this.fetch({
294 ...options,
295 meta: {
296 fetchMore: { direction: 'forward', pageParam },
297 },
298 })
299 }
300β
301 /**
302 * Fetches the previous page of the infinite query and returns a promise
303 * that resolves with the resulting `InfiniteQueryObserverResult`. The page
304 * param used for the fetch is determined by `getPreviousPageParam`, which
305 * receives the current pages/page params and whose result also determines
306 * `hasPreviousPage`. In manual mode, pass the parameter in `args[0].pageParam`.
307 * @param args - Set `cancelRefetch` to `false` to ignore the call while a fetch is running,
308 * and `throwOnError` to `true` to reject when the fetch fails.
309 * @returns A promise that resolves with the result after the previous page is fetched. With
310 * `cancelRefetch: false`, a running fetch is reused instead, so the previous page may not be fetched.
311 * @see {@link InfiniteQueryObserver#fetchNextPage}
312 * @example
313 * ```ts
314 * const { hasPreviousPage } = observer.getCurrentResult()
315 *
316 * if (hasPreviousPage) {
317 * await observer.fetchPreviousPage()
318 * }
319 * ```
320 */
321 fetchPreviousPage(
322 ...args: InfiniteQueryFetchPreviousPageArgs<TPageParam, TMode>
323 ): Promise<InfiniteQueryObserverResult<TData, TError, TPageParam, TMode>> {
324 const { pageParam, ...options } = args[0] ?? ({} as any)
325 return this.fetch({
326 ...options,
327 meta: {
328 fetchMore: { direction: 'backward', pageParam },
329 },
330 })
331 }
332β
333 protected override createResult(
334 query: Query<
335 TQueryFnData,
336 TError,
337 InfiniteData<TQueryFnData, TPageParam>,
338 TQueryKey
339 >,
340 options: QueryObserverOptions<
341 TQueryFnData,
342 TError,
343 TData,
344 InfiniteData<TQueryFnData, TPageParam>,
345 TQueryKey
346 >,
347 ): InfiniteQueryObserverResult<TData, TError, TPageParam, TMode> {
348 const { state } = query
349 const parentResult = super.createResult(query, options)
350β
351 const { isFetching, isRefetching, isError, isRefetchError } = parentResult
352 const fetchDirection = state.fetchMeta?.fetchMore?.direction
353β
354 const isFetchNextPageError = isError && fetchDirection === 'forward'
355 const isFetchingNextPage = isFetching && fetchDirection === 'forward'
356β
357 const isFetchPreviousPageError = isError && fetchDirection === 'backward'
358 const isFetchingPreviousPage = isFetching && fetchDirection === 'backward'
359β
360 const result = {
361 ...parentResult,
362 fetchNextPage: this.fetchNextPage,
363 fetchPreviousPage: this.fetchPreviousPage,
364 hasNextPage: hasNextPage(options as any, state.data),
365 hasPreviousPage: hasPreviousPage(options as any, state.data),
366 isFetchNextPageError,
367 isFetchingNextPage,
368 isFetchPreviousPageError,
369 isFetchingPreviousPage,
370 isRefetchError:
371 isRefetchError && !isFetchNextPageError && !isFetchPreviousPageError,
372 isRefetching:
373 isRefetching && !isFetchingNextPage && !isFetchingPreviousPage,
374 }
375β
376 return result as InfiniteQueryObserverResult<
377 TData,
378 TError,
379 TPageParam,
380 TMode
381 >
382 }
383}
384β
385type ReplaceReturnType<
386 TFunction extends (...args: Array<any>) => unknown,
387 TReturn,
388> = (...args: Parameters<TFunction>) => TReturn