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

InfiniteQueryObserver.md

716 lines18.6 KB

1---
2id: InfiniteQueryObserver
3title: InfiniteQueryObserver
4redirect_from:
5 - reference/InfiniteQueryObserver
6 - framework/react/reference/InfiniteQueryObserver
7---
8​
9Defined in: [packages/query-core/src/infiniteQueryObserver.ts:40](https://github.com/TanStack/query/blob/main/packages/query-core/src/infiniteQueryObserver.ts#L40)
10​
11An `InfiniteQueryObserver` extends `QueryObserver` to observe and switch
12between infinite queries. It augments the base `QueryObserverResult` with
13infinite-query-specific fields and methods, such as `hasNextPage` and
14`fetchNextPage`, and is the primitive that framework adapters (e.g.
15`useInfiniteQuery`) build their hooks on top of.
16​
17## Example
18​
19```ts
20const observer = new InfiniteQueryObserver(queryClient, {
21 queryKey: ['projects'],
22 queryFn: ({ pageParam }) => fetchProjects(pageParam),
23 initialPageParam: 0,
24 getNextPageParam: (lastPage) => lastPage.nextCursor,
25})
26​
27const unsubscribe = observer.subscribe((result) => console.log(result))
28```
29​
30## Extends
31​
32- [`QueryObserver`](QueryObserver.md)\<`TQueryFnData`, `TError`, `TData`, [`InfiniteData`](../interfaces/InfiniteData.md)\<`TQueryFnData`, `TPageParam`\>, `TQueryKey`\>
33​
34## Type Parameters
35​
36### TQueryFnData
37​
38`TQueryFnData` = `unknown`
39​
40### TError
41​
42`TError` = [`DefaultError`](../type-aliases/DefaultError.md)
43​
44### TData
45​
46`TData` = [`InfiniteData`](../interfaces/InfiniteData.md)\<`TQueryFnData`\>
47​
48### TQueryKey
49​
50`TQueryKey` *extends* [`QueryKey`](../type-aliases/QueryKey.md) = [`QueryKey`](../type-aliases/QueryKey.md)
51​
52### TPageParam
53​
54`TPageParam` = `unknown`
55​
56## Constructors
57​
58### Constructor
59​
60```ts
61new InfiniteQueryObserver<TQueryFnData, TError, TData, TQueryKey, TPageParam>(client: QueryClient, options: InfiniteQueryObserverOptions<TQueryFnData, TError, TData, TQueryKey, TPageParam>): InfiniteQueryObserver<TQueryFnData, TError, TData, TQueryKey, TPageParam>;
62```
63​
64Defined in: [packages/query-core/src/infiniteQueryObserver.ts:82](https://github.com/TanStack/query/blob/main/packages/query-core/src/infiniteQueryObserver.ts#L82)
65​
66#### Parameters
67​
68##### client
69​
70[`QueryClient`](QueryClient.md)
71​
72##### options
73​
74[`InfiniteQueryObserverOptions`](../interfaces/InfiniteQueryObserverOptions.md)\<`TQueryFnData`, `TError`, `TData`, `TQueryKey`, `TPageParam`\>
75​
76#### Returns
77​
78`InfiniteQueryObserver`\<`TQueryFnData`, `TError`, `TData`, `TQueryKey`, `TPageParam`\>
79​
80#### Overrides
81​
82[`QueryObserver`](QueryObserver.md).[`constructor`](QueryObserver.md#constructor)
83​
84## Properties
85​
86### getCurrentResult
87​
88```ts
89getCurrentResult: ReplaceReturnType<() => QueryObserverResult<TData, TError>, InfiniteQueryObserverResult<TData, TError>>;
90```
91​
92Defined in: [packages/query-core/src/infiniteQueryObserver.ts:59](https://github.com/TanStack/query/blob/main/packages/query-core/src/infiniteQueryObserver.ts#L59)
93​
94Returns the most recently computed `QueryObserverResult` for the
95observed query. This is a point-in-time read; to be notified of updates
96as they happen, subscribe to the observer instead (its inherited
97`subscribe` method).
98​
99#### Returns
100​
101The observer's latest result.
102​
103#### Example
104​
105```ts
106const result = observer.getCurrentResult()
107console.log(result.status, result.data)
108```
109​
110#### Overrides
111​
112```ts
113QueryObserver.getCurrentResult
114```
115​
116***
117​
118### options
119​
120```ts
121options: QueryObserverOptions<TQueryFnData, TError, TData, InfiniteData<TQueryFnData, TPageParam>, TQueryKey>;
122```
123​
124Defined in: [packages/query-core/src/queryObserver.ts:88](https://github.com/TanStack/query/blob/main/packages/query-core/src/queryObserver.ts#L88)
125​
126#### Inherited from
127​
128[`QueryObserver`](QueryObserver.md).[`options`](QueryObserver.md#options)
129​
130***
131​
132### subscribe
133​
134```ts
135subscribe: (listener: InfiniteQueryObserverListener) => () => void;
136```
137​
138Defined in: [packages/query-core/src/infiniteQueryObserver.ts:54](https://github.com/TanStack/query/blob/main/packages/query-core/src/infiniteQueryObserver.ts#L54)
139​
140Registers a listener to be called on every update this object notifies about. Returns a function
141that removes the listener again β€” call it to stop listening. The base class never drops a listener
142on its own, though some subclasses clear all of theirs in `destroy()`.
143​
144#### Parameters
145​
146##### listener
147​
148`InfiniteQueryObserverListener`
149​
150Called on each update, with whatever the subclass passes to its subscribers.
151​
152#### Returns
153​
154A function that removes the listener.
155​
156() => `void`
157​
158#### Example
159​
160```ts
161const unsubscribe = subscribable.subscribe(() => {
162 // react to the update
163})
164​
165unsubscribe()
166```
167​
168#### Overrides
169​
170```ts
171QueryObserver.subscribe
172```
173​
174## Methods
175​
176### destroy()
177​
178```ts
179destroy(): void;
180```
181​
182Defined in: [packages/query-core/src/queryObserver.ts:166](https://github.com/TanStack/query/blob/main/packages/query-core/src/queryObserver.ts#L166)
183​
184Stops observing the current query: clears all listeners, cancels the
185stale and refetch-interval timers, and removes this observer from the
186query it was observing.
187​
188#### Returns
189​
190`void`
191​
192#### Inherited from
193​
194[`QueryObserver`](QueryObserver.md).[`destroy`](QueryObserver.md#destroy)
195​
196***
197​
198### fetchNextPage()
199​
200```ts
201fetchNextPage(options?: FetchNextPageOptions): Promise<InfiniteQueryObserverResult<TData, TError>>;
202```
203​
204Defined in: [packages/query-core/src/infiniteQueryObserver.ts:165](https://github.com/TanStack/query/blob/main/packages/query-core/src/infiniteQueryObserver.ts#L165)
205​
206Fetches the next page of the infinite query and returns a promise that
207resolves with the resulting `InfiniteQueryObserverResult`. The page
208param used for the fetch is determined by `getNextPageParam`, which
209receives the current pages/page params and whose result also determines
210`hasNextPage`.
211​
212#### Parameters
213​
214##### options?
215​
216[`FetchNextPageOptions`](../interfaces/FetchNextPageOptions.md)
217​
218Set `cancelRefetch` to `false` to ignore the call while a fetch is running,
219and `throwOnError` to `true` to reject when the fetch fails.
220​
221#### Returns
222​
223`Promise`\<[`InfiniteQueryObserverResult`](../type-aliases/InfiniteQueryObserverResult.md)\<`TData`, `TError`\>\>
224​
225A promise that resolves with the result after the next page is fetched. With
226`cancelRefetch: false`, a running fetch is reused instead, so the next page may not be fetched.
227​
228#### See
229​
230[InfiniteQueryObserver#fetchPreviousPage](#fetchpreviouspage)
231​
232#### Example
233​
234```ts
235const { hasNextPage } = observer.getCurrentResult()
236​
237if (hasNextPage) {
238 await observer.fetchNextPage()
240```
241​
242***
243​
244### fetchOptimistic()
245​
246```ts
247fetchOptimistic(options: QueryObserverOptions<TQueryFnData, TError, TData, InfiniteData<TQueryFnData, TPageParam>, TQueryKey>): Promise<QueryObserverResult<TData, TError>>;
248```
249​
250Defined in: [packages/query-core/src/queryObserver.ts:412](https://github.com/TanStack/query/blob/main/packages/query-core/src/queryObserver.ts#L412)
251​
252Fetches a query defined by the given options without affecting this
253observer's own tracked query or result, and returns a promise that
254resolves with the `QueryObserverResult` for that fetch. This is useful
255for prefetching data that another observer (e.g. a query about to be
256navigated to) will need, ahead of time.
257​
258#### Parameters
259​
260##### options
261​
262[`QueryObserverOptions`](../interfaces/QueryObserverOptions.md)\<`TQueryFnData`, `TError`, `TData`, [`InfiniteData`](../interfaces/InfiniteData.md)\<`TQueryFnData`, `TPageParam`\>, `TQueryKey`\>
263​
264The observer options of the query to fetch.
265​
266#### Returns
267​
268`Promise`\<[`QueryObserverResult`](../type-aliases/QueryObserverResult.md)\<`TData`, `TError`\>\>
269​
270A promise that resolves with the result for the fetched query.
271​
272#### Example
273​
274```ts
275const result = await observer.fetchOptimistic({
276 queryKey: ['posts', 2],
277 queryFn: () => fetchPost(2),
278})
279console.log(result.data)
280```
281​
282#### Inherited from
283​
284[`QueryObserver`](QueryObserver.md).[`fetchOptimistic`](QueryObserver.md#fetchoptimistic)
285​
286***
287​
288### fetchPreviousPage()
289​
290```ts
291fetchPreviousPage(options?: FetchPreviousPageOptions): Promise<InfiniteQueryObserverResult<TData, TError>>;
292```
293​
294Defined in: [packages/query-core/src/infiniteQueryObserver.ts:196](https://github.com/TanStack/query/blob/main/packages/query-core/src/infiniteQueryObserver.ts#L196)
295​
296Fetches the previous page of the infinite query and returns a promise
297that resolves with the resulting `InfiniteQueryObserverResult`. The page
298param used for the fetch is determined by `getPreviousPageParam`, which
299receives the current pages/page params and whose result also determines
300`hasPreviousPage`.
301​
302#### Parameters
303​
304##### options?
305​
306[`FetchPreviousPageOptions`](../interfaces/FetchPreviousPageOptions.md)
307​
308Set `cancelRefetch` to `false` to ignore the call while a fetch is running,
309and `throwOnError` to `true` to reject when the fetch fails.
310​
311#### Returns
312​
313`Promise`\<[`InfiniteQueryObserverResult`](../type-aliases/InfiniteQueryObserverResult.md)\<`TData`, `TError`\>\>
314​
315A promise that resolves with the result after the previous page is fetched. With
316`cancelRefetch: false`, a running fetch is reused instead, so the previous page may not be fetched.
317​
318#### See
319​
320[InfiniteQueryObserver#fetchNextPage](#fetchnextpage)
321​
322#### Example
323​
324```ts
325const { hasPreviousPage } = observer.getCurrentResult()
326​
327if (hasPreviousPage) {
328 await observer.fetchPreviousPage()
330```
331​
332***
333​
334### getCurrentQuery()
335​
336```ts
337getCurrentQuery(): Query<TQueryFnData, TError, InfiniteData<TQueryFnData, TPageParam>, TQueryKey>;
338```
339​
340Defined in: [packages/query-core/src/queryObserver.ts:371](https://github.com/TanStack/query/blob/main/packages/query-core/src/queryObserver.ts#L371)
341​
342Returns the `Query` instance this observer is currently observing.
343​
344#### Returns
345​
346[`Query`](Query.md)\<`TQueryFnData`, `TError`, [`InfiniteData`](../interfaces/InfiniteData.md)\<`TQueryFnData`, `TPageParam`\>, `TQueryKey`\>
347​
348The observed query.
349​
350#### Inherited from
351​
352[`QueryObserver`](QueryObserver.md).[`getCurrentQuery`](QueryObserver.md#getcurrentquery)
353​
354***
355​
356### getOptimisticResult()
357​
358```ts
359getOptimisticResult(options: DefaultedInfiniteQueryObserverOptions<TQueryFnData, TError, TData, TQueryKey, TPageParam>): InfiniteQueryObserverResult<TData, TError>;
360```
361​
362Defined in: [packages/query-core/src/infiniteQueryObserver.ts:129](https://github.com/TanStack/query/blob/main/packages/query-core/src/infiniteQueryObserver.ts#L129)
363​
364The infinite-query counterpart of [QueryObserver#getOptimisticResult](QueryObserver.md#getoptimisticresult), marking the
365options as an infinite query before delegating to it. Called by framework adapters (e.g.
366`useInfiniteQuery`) ahead of subscribing, to compute the current `InfiniteQueryObserverResult`
367synchronously.
368​
369#### Parameters
370​
371##### options
372​
373[`DefaultedInfiniteQueryObserverOptions`](../type-aliases/DefaultedInfiniteQueryObserverOptions.md)\<`TQueryFnData`, `TError`, `TData`, `TQueryKey`, `TPageParam`\>
374​
375The defaulted infinite query observer options to compute the result for.
376​
377#### Returns
378​
379[`InfiniteQueryObserverResult`](../type-aliases/InfiniteQueryObserverResult.md)\<`TData`, `TError`\>
380​
381The result for the given options.
382​
383#### Overrides
384​
385[`QueryObserver`](QueryObserver.md).[`getOptimisticResult`](QueryObserver.md#getoptimisticresult)
386​
387***
388​
389### hasListeners()
390​
391```ts
392hasListeners(): boolean;
393```
394​
395Defined in: [packages/query-core/src/subscribable.ts:43](https://github.com/TanStack/query/blob/main/packages/query-core/src/subscribable.ts#L43)
396​
397Returns `true` while at least one listener is registered, `false` once they have all unsubscribed.
398​
399#### Returns
400​
401`boolean`
402​
403`true` if at least one listener is registered.
404​
405#### Inherited from
406​
407[`QueryObserver`](QueryObserver.md).[`hasListeners`](QueryObserver.md#haslisteners)
408​
409***
410​
411### refetch()
412​
413```ts
414refetch(options?: RefetchOptions): Promise<QueryObserverResult<TData, TError>>;
415```
416​
417Defined in: [packages/query-core/src/queryObserver.ts:387](https://github.com/TanStack/query/blob/main/packages/query-core/src/queryObserver.ts#L387)
418​
419Refetches the observed query and returns a promise that resolves with
420the resulting `QueryObserverResult`.
421​
422#### Parameters
423​
424##### options?
425​
426[`RefetchOptions`](../interfaces/RefetchOptions.md) = `{}`
427​
428Set `cancelRefetch` to `false` to keep a running fetch instead of cancelling
429it, and `throwOnError` to `true` to reject when the refetch fails.
430​
431#### Returns
432​
433`Promise`\<[`QueryObserverResult`](../type-aliases/QueryObserverResult.md)\<`TData`, `TError`\>\>
434​
435A promise that resolves with the result after the refetch.
436​
437#### Example
438​
439```ts
440const result = await observer.refetch({ cancelRefetch: false })
441console.log(result.data)
442```
443​
444#### Inherited from
445​
446[`QueryObserver`](QueryObserver.md).[`refetch`](QueryObserver.md#refetch)
447​
448***
449​
450### setOptions()
451​
452```ts
453setOptions(options: InfiniteQueryObserverOptions<TQueryFnData, TError, TData, TQueryKey, TPageParam>): void;
454```
455​
456Defined in: [packages/query-core/src/infiniteQueryObserver.ts:108](https://github.com/TanStack/query/blob/main/packages/query-core/src/infiniteQueryObserver.ts#L108)
457​
458Updates the observer's options. Behaves the same as
459`QueryObserver.setOptions`, additionally marking the options as
460belonging to an infinite query before delegating to the base
461implementation.
462​
463#### Parameters
464​
465##### options
466​
467[`InfiniteQueryObserverOptions`](../interfaces/InfiniteQueryObserverOptions.md)\<`TQueryFnData`, `TError`, `TData`, `TQueryKey`, `TPageParam`\>
468​
469The new infinite query observer options.
470​
471#### Returns
472​
473`void`
474​
475#### Overrides
476​
477[`QueryObserver`](QueryObserver.md).[`setOptions`](QueryObserver.md#setoptions)
478​
479***
480​
481### shouldFetchOnReconnect()
482​
483```ts
484shouldFetchOnReconnect(): boolean;
485```
486​
487Defined in: [packages/query-core/src/queryObserver.ts:139](https://github.com/TanStack/query/blob/main/packages/query-core/src/queryObserver.ts#L139)
488​
489Returns whether the observed query is currently stale and configured
490(via the `refetchOnReconnect` option) to refetch when the network
491reconnects.
492​
493#### Returns
494​
495`boolean`
496​
497`true` if the observer should refetch the query on reconnect.
498​
499#### Inherited from
500​
501[`QueryObserver`](QueryObserver.md).[`shouldFetchOnReconnect`](QueryObserver.md#shouldfetchonreconnect)
502​
503***
504​
505### shouldFetchOnWindowFocus()
506​
507```ts
508shouldFetchOnWindowFocus(): boolean;
509```
510​
511Defined in: [packages/query-core/src/queryObserver.ts:153](https://github.com/TanStack/query/blob/main/packages/query-core/src/queryObserver.ts#L153)
512​
513Returns whether the observed query is currently stale and configured
514(via the `refetchOnWindowFocus` option) to refetch when the window
515regains focus.
516​
517#### Returns
518​
519`boolean`
520​
521`true` if the observer should refetch the query on window focus.
522​
523#### Inherited from
524​
525[`QueryObserver`](QueryObserver.md).[`shouldFetchOnWindowFocus`](QueryObserver.md#shouldfetchonwindowfocus)
526​
527***
528​
529### trackProp()
530​
531```ts
532trackProp(key:
533 | "error"
534 | "data"
535 | "isError"
536 | "isPending"
537 | "isLoading"
538 | "isLoadingError"
539 | "isRefetchError"
540 | "isSuccess"
541 | "isPlaceholderData"
542 | "status"
543 | "dataUpdatedAt"
544 | "errorUpdatedAt"
545 | "failureCount"
546 | "failureReason"
547 | "errorUpdateCount"
548 | "isFetched"
549 | "isFetchedAfterMount"
550 | "isFetching"
551 | "isInitialLoading"
552 | "isPaused"
553 | "isRefetching"
554 | "isStale"
555 | "isEnabled"
556 | "refetch"
557 | "fetchStatus"): void;
558```
559​
560Defined in: [packages/query-core/src/queryObserver.ts:363](https://github.com/TanStack/query/blob/main/packages/query-core/src/queryObserver.ts#L363)
561​
562Records that the given `QueryObserverResult` property was read, so a subsequent update only
563notifies this observer if a tracked property actually changed. Normally called indirectly via
564[QueryObserver#trackResult](QueryObserver.md#trackresult)'s proxy; exposed directly for adapters that track property
565access themselves (e.g. through their own reactivity system) instead of via the proxy.
566​
567#### Parameters
568​
569##### key
570​
571 \| `"error"`
572 \| `"data"`
573 \| `"isError"`
574 \| `"isPending"`
575 \| `"isLoading"`
576 \| `"isLoadingError"`
577 \| `"isRefetchError"`
578 \| `"isSuccess"`
579 \| `"isPlaceholderData"`
580 \| `"status"`
581 \| `"dataUpdatedAt"`
582 \| `"errorUpdatedAt"`
583 \| `"failureCount"`
584 \| `"failureReason"`
585 \| `"errorUpdateCount"`
586 \| `"isFetched"`
587 \| `"isFetchedAfterMount"`
588 \| `"isFetching"`
589 \| `"isInitialLoading"`
590 \| `"isPaused"`
591 \| `"isRefetching"`
592 \| `"isStale"`
593 \| `"isEnabled"`
594 \| `"refetch"`
595 \| `"fetchStatus"`
596​
597The name of the property that was read.
598​
599#### Returns
600​
601`void`
602​
603#### Inherited from
604​
605[`QueryObserver`](QueryObserver.md).[`trackProp`](QueryObserver.md#trackprop)
606​
607***
608​
609### trackResult()
610​
611```ts
612trackResult(result: QueryObserverResult<TData, TError>, onPropTracked?: (key:
613 | "error"
614 | "data"
615 | "isError"
616 | "isPending"
617 | "isLoading"
618 | "isLoadingError"
619 | "isRefetchError"
620 | "isSuccess"
621 | "isPlaceholderData"
622 | "status"
623 | "dataUpdatedAt"
624 | "errorUpdatedAt"
625 | "failureCount"
626 | "failureReason"
627 | "errorUpdateCount"
628 | "isFetched"
629 | "isFetchedAfterMount"
630 | "isFetching"
631 | "isInitialLoading"
632 | "isPaused"
633 | "isRefetching"
634 | "isStale"
635 | "isEnabled"
636 | "refetch"
637| "fetchStatus") => void): QueryObserverResult<TData, TError>;
638```
639​
640Defined in: [packages/query-core/src/queryObserver.ts:343](https://github.com/TanStack/query/blob/main/packages/query-core/src/queryObserver.ts#L343)
641​
642Wraps a `QueryObserverResult` in a `Proxy` that records which properties are read, via
643[QueryObserver#trackProp](QueryObserver.md#trackprop) (and an optional `onPropTracked` callback). Used by framework
644adapters when `notifyOnChangeProps` is not set, to implement its default "only re-render on
645properties you actually read" behavior.
646​
647#### Parameters
648​
649##### result
650​
651[`QueryObserverResult`](../type-aliases/QueryObserverResult.md)\<`TData`, `TError`\>
652​
653The result to wrap.
654​
655##### onPropTracked?
656​
657(`key`:
658 \| `"error"`
659 \| `"data"`
660 \| `"isError"`
661 \| `"isPending"`
662 \| `"isLoading"`
663 \| `"isLoadingError"`
664 \| `"isRefetchError"`
665 \| `"isSuccess"`
666 \| `"isPlaceholderData"`
667 \| `"status"`
668 \| `"dataUpdatedAt"`
669 \| `"errorUpdatedAt"`
670 \| `"failureCount"`
671 \| `"failureReason"`
672 \| `"errorUpdateCount"`
673 \| `"isFetched"`
674 \| `"isFetchedAfterMount"`
675 \| `"isFetching"`
676 \| `"isInitialLoading"`
677 \| `"isPaused"`
678 \| `"isRefetching"`
679 \| `"isStale"`
680 \| `"isEnabled"`
681 \| `"refetch"`
682 \| `"fetchStatus"`) => `void`
683​
684Called with the name of each property that is read.
685​
686#### Returns
687​
688[`QueryObserverResult`](../type-aliases/QueryObserverResult.md)\<`TData`, `TError`\>
689​
690A proxy of `result` that tracks property reads.
691​
692#### Inherited from
693​
694[`QueryObserver`](QueryObserver.md).[`trackResult`](QueryObserver.md#trackresult)
695​
696***
697​
698### updateResult()
699​
700```ts
701updateResult(): void;
702```
703​
704Defined in: [packages/query-core/src/queryObserver.ts:765](https://github.com/TanStack/query/blob/main/packages/query-core/src/queryObserver.ts#L765)
705​
706Recomputes and stores the current result from the current query/options, notifying listeners
707if it changed. Framework adapters call this right after subscribing to make sure no query
708update was missed in the gap between creating the observer and subscribing to it.
709​
710#### Returns
711​
712`void`
713​
714#### Inherited from
715​
716[`QueryObserver`](QueryObserver.md).[`updateResult`](QueryObserver.md#updateresult)