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

infiniteQueryObserver.ts

286 lines8.8 KB

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