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