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

InfiniteQueryObserver.md

713 lines18.5 KB

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