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 DefaultedInfiniteQueryObserverOptions,
7 FetchNextPageOptions,
8 FetchPreviousPageOptions,
9 InfiniteData,
10 InfiniteQueryObserverBaseResult,
11 InfiniteQueryObserverOptions,
12 InfiniteQueryObserverResult,
13 QueryKey,
14} from './types'
15import type { QueryClient } from './queryClient'
16import type { Query } from './query'
17β
18type InfiniteQueryObserverListener<TData, TError> = (
19 result: InfiniteQueryObserverResult<TData, TError>,
20) => void
21β
22/**
23 * An `InfiniteQueryObserver` extends `QueryObserver` to observe and switch
24 * between infinite queries. It augments the base `QueryObserverResult` with
25 * infinite-query-specific fields and methods, such as `hasNextPage` and
26 * `fetchNextPage`, and is the primitive that framework adapters (e.g.
27 * `useInfiniteQuery`) build their hooks on top of.
28 *
29 * @example
30 * ;```ts
31 * const observer = new InfiniteQueryObserver(queryClient, {
32 * queryKey: ['projects'],
33 * queryFn: ({ pageParam }) => fetchProjects(pageParam),
34 * initialPageParam: 0,
35 * getNextPageParam: (lastPage) => lastPage.nextCursor,
36 * })
37 *
38 * const unsubscribe = observer.subscribe((result) => console.log(result))
39 * ```
40 */
41export class InfiniteQueryObserver<
42 TQueryFnData = unknown,
43 TError = DefaultError,
44 TData = InfiniteData<TQueryFnData>,
45 TQueryKey extends QueryKey = QueryKey,
46 TPageParam = unknown,
47> extends QueryObserver<
48 TQueryFnData,
49 TError,
50 TData,
51 InfiniteData<TQueryFnData, TPageParam>,
52 TQueryKey
53> {
54 // Type override
55 override subscribe!: Subscribable<
56 InfiniteQueryObserverListener<TData, TError>
57 >['subscribe']
58β
59 // Type override
60 override getCurrentResult!: ReplaceReturnType<
61 QueryObserver<
62 TQueryFnData,
63 TError,
64 TData,
65 InfiniteData<TQueryFnData, TPageParam>,
66 TQueryKey
67 >['getCurrentResult'],
68 InfiniteQueryObserverResult<TData, TError>
69 >
70β
71 // Type override
72 protected override fetch!: ReplaceReturnType<
73 QueryObserver<
74 TQueryFnData,
75 TError,
76 TData,
77 InfiniteData<TQueryFnData, TPageParam>,
78 TQueryKey
79 >['fetch'],
80 Promise<InfiniteQueryObserverResult<TData, TError>>
81 >
82β
83 constructor(
84 client: QueryClient,
85 options: InfiniteQueryObserverOptions<
86 TQueryFnData,
87 TError,
88 TData,
89 TQueryKey,
90 TPageParam
91 >,
92 ) {
93 super(client, options)
94 }
95β
96 protected override bindMethods(): void {
97 super.bindMethods()
98 this.fetchNextPage = this.fetchNextPage.bind(this)
99 this.fetchPreviousPage = this.fetchPreviousPage.bind(this)
100 }
101β
102 /**
103 * Updates the observer's options. Behaves the same as
104 * `QueryObserver.setOptions`, additionally marking the options as belonging
105 * to an infinite query before delegating to the base implementation.
106 *
107 * @param options - The new infinite query observer options.
108 */
109 override setOptions(
110 options: InfiniteQueryObserverOptions<
111 TQueryFnData,
112 TError,
113 TData,
114 TQueryKey,
115 TPageParam
116 >,
117 ): void {
118 options._type = 'infinite'
119 super.setOptions(options)
120 }
121β
122 /**
123 * The infinite-query counterpart of {@link QueryObserver#getOptimisticResult},
124 * marking the options as an infinite query before delegating to it. Called by
125 * framework adapters (e.g. `useInfiniteQuery`) ahead of subscribing, to
126 * compute the current `InfiniteQueryObserverResult` synchronously.
127 *
128 * @param options - The defaulted infinite query observer options to compute
129 * the result for.
130 * @returns The result for the given options.
131 */
132 override getOptimisticResult(
133 options: DefaultedInfiniteQueryObserverOptions<
134 TQueryFnData,
135 TError,
136 TData,
137 TQueryKey,
138 TPageParam
139 >,
140 ): InfiniteQueryObserverResult<TData, TError> {
141 options._type = 'infinite'
142 return super.getOptimisticResult(options) as InfiniteQueryObserverResult<
143 TData,
144 TError
145 >
146 }
147β
148 /**
149 * Fetches the next page of the infinite query and returns a promise that
150 * resolves with the resulting `InfiniteQueryObserverResult`. The page param
151 * used for the fetch is determined by `getNextPageParam`, which receives the
152 * current pages/page params and whose result also determines `hasNextPage`.
153 *
154 * @example
155 * ;```ts
156 * const { hasNextPage } = observer.getCurrentResult()
157 *
158 * if (hasNextPage) {
159 * await observer.fetchNextPage()
160 * }
161 * ```
162 *
163 * @param options - Set `cancelRefetch` to `false` to ignore the call while a
164 * fetch is running, and `throwOnError` to `true` to reject when the fetch
165 * fails.
166 * @returns A promise that resolves with the result after the next page is
167 * fetched. With `cancelRefetch: false`, a running fetch is reused instead,
168 * so the next page may not be fetched.
169 * @see {@link InfiniteQueryObserver#fetchPreviousPage}
170 */
171 fetchNextPage(
172 options?: FetchNextPageOptions,
173 ): Promise<InfiniteQueryObserverResult<TData, TError>> {
174 return this.fetch({
175 ...options,
176 meta: {
177 fetchMore: { direction: 'forward' },
178 },
179 })
180 }
181β
182 /**
183 * Fetches the previous page of the infinite query and returns a promise that
184 * resolves with the resulting `InfiniteQueryObserverResult`. The page param
185 * used for the fetch is determined by `getPreviousPageParam`, which receives
186 * the current pages/page params and whose result also determines
187 * `hasPreviousPage`.
188 *
189 * @example
190 * ;```ts
191 * const { hasPreviousPage } = observer.getCurrentResult()
192 *
193 * if (hasPreviousPage) {
194 * await observer.fetchPreviousPage()
195 * }
196 * ```
197 *
198 * @param options - Set `cancelRefetch` to `false` to ignore the call while a
199 * fetch is running, and `throwOnError` to `true` to reject when the fetch
200 * fails.
201 * @returns A promise that resolves with the result after the previous page is
202 * fetched. With `cancelRefetch: false`, a running fetch is reused instead,
203 * so the previous page may not be fetched.
204 * @see {@link InfiniteQueryObserver#fetchNextPage}
205 */
206 fetchPreviousPage(
207 options?: FetchPreviousPageOptions,
208 ): Promise<InfiniteQueryObserverResult<TData, TError>> {
209 return this.fetch({
210 ...options,
211 meta: {
212 fetchMore: { direction: 'backward' },
213 },
214 })
215 }
216β
217 protected override createResult(
218 query: Query<
219 TQueryFnData,
220 TError,
221 InfiniteData<TQueryFnData, TPageParam>,
222 TQueryKey
223 >,
224 options: InfiniteQueryObserverOptions<
225 TQueryFnData,
226 TError,
227 TData,
228 TQueryKey,
229 TPageParam
230 >,
231 ): InfiniteQueryObserverResult<TData, TError> {
232 const { state } = query
233 const parentResult = super.createResult(query, options)
234β
235 const { isFetching, isRefetching, isError, isRefetchError } = parentResult
236 const fetchDirection = state.fetchMeta?.fetchMore?.direction
237β
238 const isFetchNextPageError = isError && fetchDirection === 'forward'
239 const isFetchingNextPage = isFetching && fetchDirection === 'forward'
240β
241 const isFetchPreviousPageError = isError && fetchDirection === 'backward'
242 const isFetchingPreviousPage = isFetching && fetchDirection === 'backward'
243β
244 const result: InfiniteQueryObserverBaseResult<TData, TError> = {
245 ...parentResult,
246 fetchNextPage: this.fetchNextPage,
247 fetchPreviousPage: this.fetchPreviousPage,
248 hasNextPage: hasNextPage(options, state.data),
249 hasPreviousPage: hasPreviousPage(options, state.data),
250 isFetchNextPageError,
251 isFetchingNextPage,
252 isFetchPreviousPageError,
253 isFetchingPreviousPage,
254 isRefetchError:
255 isRefetchError && !isFetchNextPageError && !isFetchPreviousPageError,
256 isRefetching:
257 isRefetching && !isFetchingNextPage && !isFetchingPreviousPage,
258 }
259β
260 return result as InfiniteQueryObserverResult<TData, TError>
261 }
262}
263β
264type ReplaceReturnType<
265 TFunction extends (...args: Array<any>) => unknown,
266 TReturn,
267> = (...args: Parameters<TFunction>) => TReturn