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

inject-infinite-query.ts

333 lines11.6 KB

1import { assertInInjectionContext, untracked } from '@angular/core'
2import { InfiniteQueryObserver } from '@tanstack/query-core'
3import { injectBaseQuery } from './inject-base-query'
4import { injectQueryZone } from './utils/inject-query-zone'
5import { infiniteQueryResultFields } from './utils/result-fields'
6import { signalProxy } from './utils/signal-proxy'
7import type { Signal } from '@angular/core'
8import type {
9 DefaultError,
10 FetchNextPageOptions,
11 FetchPreviousPageOptions,
12 InfiniteData,
13 InfiniteQueryObserverResult,
14 QueryKey,
15 QueryObserver,
16 RefetchOptions,
17} from '@tanstack/query-core'
18import type {
19 DefinedInitialDataInfiniteOptions,
20 UndefinedInitialDataInfiniteOptions,
21} from './infinite-query-options'
22import type {
23 CreateInfiniteQueryOptions,
24 CreateInfiniteQueryResult,
25 DefinedCreateInfiniteQueryResult,
26} from './types'
27​
28/**
29 * The options for `injectInfiniteQuery` are identical to `injectQuery`, with the addition of
30 * `initialPageParam`, `getNextPageParam`, `getPreviousPageParam`, and `maxPages`. Infinite queries can
31 * additively "load more" data onto an existing set of data, or "infinite scroll".
32 *
33 * This overload is selected when `initialData` is known to be defined on the options returned by
34 * `optionsFn`, so the resulting `data` signal is never `undefined` (unless a `select` changes
35 * `TData` to include `undefined`).
36 * @param optionsFn - A function returning the {@link DefinedInitialDataInfiniteOptions} to use β€”
37 * everything you can pass to `injectInfiniteQuery`, with `initialData` known to be defined. Similar to
38 * `computed` from Angular, this function runs in the reactive context, so signals read inside it drive the
39 * query.
40 * @returns The same signals as `injectQuery`, with the addition of `fetchNextPage`, `fetchPreviousPage`,
41 * `hasNextPage`, `hasPreviousPage`, `isFetchingNextPage`, and `isFetchingPreviousPage`. `data().pages` and
42 * `data().pageParams` are also added, as long as a `select` doesn't change `TData` away from its default
43 * `InfiniteData<TQueryFnData>` shape.
44 * @remarks Keep in mind that imperative fetch calls, such as `fetchNextPage`, may interfere with the default
45 * refetch behavior, resulting in outdated data. Make sure to call these functions only in response to user
46 * actions, or add conditions like `hasNextPage() && !isFetching()`.
47 * @see https://tanstack.com/query/latest/docs/framework/angular/guides/infinite-queries
48 * @see {@link infiniteQueryOptions} to share these options between `injectInfiniteQuery` and imperative APIs
49 * like `queryClient.infiniteQuery`.
50 * @example
51 * ```angular-ts
52 * @Component({
53 * selector: 'projects',
54 * template: `
55 * <!-- projectsQuery.data() is never undefined, thanks to initialData β€” even if a
56 * refetch fails, so the list stays visible alongside the error. -->
57 * <ul>
58 * @for (page of projectsQuery.data().pages; track $index) {
59 * @for (project of page.projects; track project.id) {
60 * <li>{{ project.name }}</li>
61 * }
62 * }
63 * </ul>
64 * `,
65 * })
66 * export class Projects {
67 * readonly projectsQuery = injectInfiniteQuery(() => ({
68 * queryKey: ['projects'],
69 * queryFn: ({ pageParam }) => fetchProjects(pageParam),
70 * initialPageParam: 0,
71 * getNextPageParam: (lastPage) => lastPage.nextId,
72 * initialData: { pages: [], pageParams: [] },
73 * }))
74 * }
75 * ```
76 */
77export function injectInfiniteQuery<
78 TQueryFnData,
79 TError = DefaultError,
80 TData = InfiniteData<TQueryFnData>,
81 TQueryKey extends QueryKey = QueryKey,
82 TPageParam = unknown,
83>(
84 optionsFn: () => DefinedInitialDataInfiniteOptions<
85 TQueryFnData,
86 TError,
87 TData,
88 TQueryKey,
89 TPageParam
90 >,
91): DefinedCreateInfiniteQueryResult<TData, TError>
92​
93/**
94 * Injects an infinite query: a declarative dependency on an asynchronous source of data that is tied to a
95 * unique key. Infinite queries can additively "load more" data onto an existing set of data, or
96 * "infinite scroll".
97 * @param optionsFn - A function returning the {@link UndefinedInitialDataInfiniteOptions} to use
98 * β€” everything you can pass to `injectInfiniteQuery`. Similar to `computed` from Angular, this function runs
99 * in the reactive context, so signals read inside it drive the query.
100 * @returns The same signals as `injectQuery`, with the addition of `fetchNextPage`, `fetchPreviousPage`,
101 * `hasNextPage`, `hasPreviousPage`, `isFetchingNextPage`, and `isFetchingPreviousPage`. `data().pages` and
102 * `data().pageParams` are also added, as long as a `select` doesn't change `TData` away from its default
103 * `InfiniteData<TQueryFnData>` shape.
104 * @remarks Keep in mind that imperative fetch calls, such as `fetchNextPage`, may interfere with the default
105 * refetch behavior, resulting in outdated data. Make sure to call these functions only in response to user
106 * actions, or add conditions like `hasNextPage() && !isFetching()`. `queryFn: skipToken` is also accepted,
107 * shown below.
108 * @see https://tanstack.com/query/latest/docs/framework/angular/guides/infinite-queries
109 * @see {@link infiniteQueryOptions} to share these options between `injectInfiniteQuery` and imperative APIs
110 * like `queryClient.infiniteQuery`.
111 * @example
112 * Fetching the next page from a button click:
113 * ```angular-ts
114 * @Component({
115 * selector: 'projects-list',
116 * template: `
117 * <ul>
118 * @for (page of projectsQuery.data()?.pages; track $index) {
119 * @for (project of page.projects; track project.id) {
120 * <li>{{ project.name }}</li>
121 * }
122 * }
123 * </ul>
124 * <button
125 * [disabled]="!projectsQuery.hasNextPage() || projectsQuery.isFetching()"
126 * (click)="projectsQuery.fetchNextPage()"
127 * >
128 * Load More
129 * </button>
130 * `,
131 * })
132 * export class ProjectsList {
133 * readonly projectsQuery = injectInfiniteQuery(() => ({
134 * queryKey: ['projects'],
135 * queryFn: ({ pageParam }) => fetchProjects(pageParam),
136 * initialPageParam: 0,
137 * getNextPageParam: (lastPage) => lastPage.nextId,
138 * }))
139 * }
140 * ```
141 * @example
142 * Fetching the next page automatically as the user scrolls, using an `IntersectionObserver` on a sentinel
143 * element after the list:
144 * ```angular-ts
145 * @Component({
146 * selector: 'projects-list',
147 * template: `
148 * <ul>
149 * @for (page of projectsQuery.data()?.pages; track $index) {
150 * @for (project of page.projects; track project.id) {
151 * <li>{{ project.name }}</li>
152 * }
153 * }
154 * </ul>
155 * <div #sentinel>{{ projectsQuery.isFetchingNextPage() ? 'Loading more...' : '' }}</div>
156 * `,
157 * })
158 * export class ProjectsList {
159 * readonly sentinel = viewChild<ElementRef<HTMLElement>>('sentinel')
160 *
161 * readonly projectsQuery = injectInfiniteQuery(() => ({
162 * queryKey: ['projects'],
163 * queryFn: ({ pageParam }) => fetchProjects(pageParam),
164 * initialPageParam: 0,
165 * getNextPageParam: (lastPage) => lastPage.nextId,
166 * }))
167 *
168 * constructor() {
169 * effect((onCleanup) => {
170 * const sentinel = this.sentinel()?.nativeElement
171 * if (
172 * sentinel == null ||
173 * !this.projectsQuery.hasNextPage() ||
174 * this.projectsQuery.isFetching()
175 * ) {
176 * return
177 * }
178 *
179 * const observer = new IntersectionObserver(([entry]) => {
180 * if (entry?.isIntersecting) this.projectsQuery.fetchNextPage()
181 * })
182 * observer.observe(sentinel)
183 *
184 * onCleanup(() => observer.disconnect())
185 * })
186 * }
187 * }
188 * ```
189 * @example
190 * A query that's disabled, type safe, until `postId` is set β€” pass `skipToken` as `queryFn` instead of
191 * setting `enabled: false`:
192 * ```angular-ts
193 * @Component({
194 * selector: 'comments',
195 * template: `
196 * @if (postId() == null) {
197 * Select a post
198 * } @else if (commentsQuery.isPending()) {
199 * Loading...
200 * } @else if (commentsQuery.isError()) {
201 * <span>Error: {{ commentsQuery.error()?.message }}</span>
202 * } @else {
203 * <ul>
204 * @for (page of commentsQuery.data().pages; track $index) {
205 * @for (comment of page.comments; track comment.id) {
206 * <li>{{ comment.text }}</li>
207 * }
208 * }
209 * </ul>
210 * }
211 * `,
212 * })
213 * export class Comments {
214 * readonly postId = signal<string | undefined>(undefined)
215 *
216 * readonly commentsQuery = injectInfiniteQuery(() => ({
217 * queryKey: ['post', this.postId(), 'comments'],
218 * queryFn:
219 * this.postId() != null
220 * ? ({ pageParam }) => fetchComments(this.postId()!, pageParam)
221 * : skipToken,
222 * initialPageParam: 0,
223 * getNextPageParam: (lastPage) => lastPage.nextId,
224 * }))
225 * }
226 * ```
227 */
228export function injectInfiniteQuery<
229 TQueryFnData,
230 TError = DefaultError,
231 TData = InfiniteData<TQueryFnData>,
232 TQueryKey extends QueryKey = QueryKey,
233 TPageParam = unknown,
234>(
235 optionsFn: () => UndefinedInitialDataInfiniteOptions<
236 TQueryFnData,
237 TError,
238 TData,
239 TQueryKey,
240 TPageParam
241 >,
242): CreateInfiniteQueryResult<TData, TError>
243​
244/**
245 * This overload accepts the general {@link CreateInfiniteQueryOptions} shape rather than the
246 * `initialData`-aware overloads above, so whether `data` is defined can't be inferred from the call site β€”
247 * useful when wrapping `injectInfiniteQuery` in your own helper function that forwards caller-provided
248 * options.
249 * @param optionsFn - A function that returns infinite query options. Similar to `computed` from
250 * Angular, this function runs in the reactive context, so signals read inside it drive the query.
251 * @returns The infinite query result.
252 * @see https://tanstack.com/query/latest/docs/framework/angular/guides/infinite-queries
253 */
254export function injectInfiniteQuery<
255 TQueryFnData,
256 TError = DefaultError,
257 TData = InfiniteData<TQueryFnData>,
258 TQueryKey extends QueryKey = QueryKey,
259 TPageParam = unknown,
260>(
261 optionsFn: () => CreateInfiniteQueryOptions<
262 TQueryFnData,
263 TError,
264 TData,
265 TQueryKey,
266 TPageParam
267 >,
268): CreateInfiniteQueryResult<TData, TError>
269​
270export function injectInfiniteQuery<
271 TQueryFnData,
272 TError = DefaultError,
273 TData = InfiniteData<TQueryFnData>,
274 TQueryKey extends QueryKey = QueryKey,
275 TPageParam = unknown,
276>(
277 optionsFn: () =>
278 | DefinedInitialDataInfiniteOptions<
279 TQueryFnData,
280 TError,
281 TData,
282 TQueryKey,
283 TPageParam
284 >
285 | CreateInfiniteQueryOptions<
286 TQueryFnData,
287 TError,
288 TData,
289 TQueryKey,
290 TPageParam
291 >,
292):
293 | DefinedCreateInfiniteQueryResult<TData, TError>
294 | CreateInfiniteQueryResult<TData, TError> {
295 if (typeof ngDevMode === 'undefined' || ngDevMode) {
296 assertInInjectionContext(injectInfiniteQuery)
297 }
298 const outsideZone = injectQueryZone()
299 const [resultSignal, getObserver] = injectBaseQuery(
300 optionsFn,
301 InfiniteQueryObserver as typeof QueryObserver,
302 )
303 const getInfiniteObserver = () =>
304 getObserver() as InfiniteQueryObserver<
305 TQueryFnData,
306 TError,
307 TData,
308 TQueryKey,
309 TPageParam
310 >
311 return Object.assign(
312 signalProxy(
313 resultSignal as Signal<InfiniteQueryObserverResult<TData, TError>>,
314 infiniteQueryResultFields,
315 ),
316 {
317 refetch: (options?: RefetchOptions) =>
318 outsideZone(() =>
319 untracked(() => getInfiniteObserver().refetch(options)),
320 ),
321 fetchNextPage: (options?: FetchNextPageOptions) =>
322 outsideZone(() =>
323 untracked(() => getInfiniteObserver().fetchNextPage(options)),
324 ),
325 fetchPreviousPage: (options?: FetchPreviousPageOptions) =>
326 outsideZone(() =>
327 untracked(() => getInfiniteObserver().fetchPreviousPage(options)),
328 ),
329 },
330 ) as unknown as
331 | DefinedCreateInfiniteQueryResult<TData, TError>
332 | CreateInfiniteQueryResult<TData, TError>