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

inject-infinite-query.ts

515 lines17.6 KB

1import { InfiniteQueryObserver } from '@tanstack/query-core'
2import {
3 Injector,
4 assertInInjectionContext,
5 inject,
6 runInInjectionContext,
7} from '@angular/core'
8import { createBaseQuery } from './create-base-query'
9import type {
10 DefaultError,
11 InfiniteData,
12 InfiniteQueryMode,
13 QueryKey,
14} from '@tanstack/query-core'
15import type {
16 CreateInfiniteQueryOptions,
17 CreateInfiniteQueryResult,
18 DefinedCreateInfiniteQueryResult,
19} from './types'
20import type {
21 DefinedInitialDataInfiniteOptions,
22 ManualDefinedInitialDataInfiniteOptions,
23 ManualUndefinedInitialDataInfiniteOptions,
24 UndefinedInitialDataInfiniteOptions,
25} from './infinite-query-options'
26​
27/**
28 * Options for `injectInfiniteQuery`, passed after the function that returns the infinite
29 * query options.
30 */
31export interface InjectInfiniteQueryOptions {
32 /**
33 * The `Injector` in which to create the infinite query.
34 *
35 * If this is not provided, the current injection context will be used instead (via `inject`).
36 */
37 injector?: Injector
39​
40/**
41 * Injects an infinite query: a declarative dependency on an asynchronous source of data that is tied to a unique key.
42 * Infinite queries can additively "load more" data onto an existing set of data or "infinite scroll"
43 *
44 * **Basic example**
45 * ```ts
46 * class ServiceOrComponent {
47 * query = injectInfiniteQuery(() => ({
48 * queryKey: ['projects'],
49 * queryFn: ({ pageParam }) =>
50 * this.#http.get<Response>('/api/projects?cursor=' + pageParam),
51 * initialPageParam: 0,
52 * getNextPageParam: (lastPage) => lastPage.nextCursor,
53 * }))
54 * }
55 * ```
56 *
57 * Similar to `computed` from Angular, the function passed to `injectInfiniteQuery` will be run in the reactive context.
58 * In the example below, the query will be automatically enabled and executed when the filter signal changes
59 * to a truthy value. When the filter signal changes back to a falsy value, the query will be disabled.
60 *
61 * **Reactive example**
62 * ```ts
63 * class ServiceOrComponent {
64 * filter = signal('')
65 *
66 * projectsQuery = injectInfiniteQuery(() => ({
67 * queryKey: ['projects', this.filter()],
68 * queryFn: ({ pageParam }) => fetchProjects(this.filter(), pageParam),
69 * initialPageParam: 0,
70 * getNextPageParam: (lastPage) => lastPage.nextCursor,
71 * enabled: !!this.filter(),
72 * }))
73 * }
74 * ```
75 * @param injectInfiniteQueryFn - A function that returns infinite query options.
76 * @param options - Additional configuration.
77 * @returns The infinite query result.
78 * @see https://tanstack.com/query/latest/docs/framework/angular/guides/infinite-queries
79 */
80export function injectInfiniteQuery<
81 TQueryFnData,
82 TError = DefaultError,
83 TData = InfiniteData<TQueryFnData>,
84 TQueryKey extends QueryKey = QueryKey,
85 TPageParam = unknown,
86>(
87 injectInfiniteQueryFn: () => ManualDefinedInitialDataInfiniteOptions<
88 TQueryFnData,
89 TError,
90 TData,
91 TQueryKey,
92 TPageParam
93 >,
94 options?: InjectInfiniteQueryOptions,
95): DefinedCreateInfiniteQueryResult<
96 TData,
97 TError,
98 TPageParam,
99 InfiniteQueryMode
101/**
102 * Injects an infinite query: a declarative dependency on an asynchronous source of data that is tied to a unique key.
103 * Infinite queries can additively "load more" data onto an existing set of data or "infinite scroll"
104 *
105 * **Basic example**
106 * ```ts
107 * class ServiceOrComponent {
108 * query = injectInfiniteQuery(() => ({
109 * queryKey: ['projects'],
110 * queryFn: ({ pageParam }) =>
111 * this.#http.get<Response>('/api/projects?cursor=' + pageParam),
112 * initialPageParam: 0,
113 * getNextPageParam: (lastPage) => lastPage.nextCursor,
114 * }))
115 * }
116 * ```
117 *
118 * Similar to `computed` from Angular, the function passed to `injectInfiniteQuery` will be run in the reactive context.
119 * In the example below, the query will be automatically enabled and executed when the filter signal changes
120 * to a truthy value. When the filter signal changes back to a falsy value, the query will be disabled.
121 *
122 * **Reactive example**
123 * ```ts
124 * class ServiceOrComponent {
125 * filter = signal('')
126 *
127 * projectsQuery = injectInfiniteQuery(() => ({
128 * queryKey: ['projects', this.filter()],
129 * queryFn: ({ pageParam }) => fetchProjects(this.filter(), pageParam),
130 * initialPageParam: 0,
131 * getNextPageParam: (lastPage) => lastPage.nextCursor,
132 * enabled: !!this.filter(),
133 * }))
134 * }
135 * ```
136 * @param injectInfiniteQueryFn - A function that returns infinite query options.
137 * @param options - Additional configuration.
138 * @returns The infinite query result.
139 * @see https://tanstack.com/query/latest/docs/framework/angular/guides/infinite-queries
140 */
141export function injectInfiniteQuery<
142 TQueryFnData,
143 TError = DefaultError,
144 TData = InfiniteData<TQueryFnData>,
145 TQueryKey extends QueryKey = QueryKey,
146 TPageParam = unknown,
147>(
148 injectInfiniteQueryFn: () => DefinedInitialDataInfiniteOptions<
149 TQueryFnData,
150 TError,
151 TData,
152 TQueryKey,
153 TPageParam,
154 undefined
155 >,
156 options?: InjectInfiniteQueryOptions,
157): DefinedCreateInfiniteQueryResult<TData, TError, TPageParam, undefined>
158/**
159 * Injects an infinite query: a declarative dependency on an asynchronous source of data that is tied to a unique key.
160 * Infinite queries can additively "load more" data onto an existing set of data or "infinite scroll"
161 *
162 * **Basic example**
163 * ```ts
164 * class ServiceOrComponent {
165 * query = injectInfiniteQuery(() => ({
166 * queryKey: ['projects'],
167 * queryFn: ({ pageParam }) =>
168 * this.#http.get<Response>('/api/projects?cursor=' + pageParam),
169 * initialPageParam: 0,
170 * getNextPageParam: (lastPage) => lastPage.nextCursor,
171 * }))
172 * }
173 * ```
174 *
175 * Similar to `computed` from Angular, the function passed to `injectInfiniteQuery` will be run in the reactive context.
176 * In the example below, the query will be automatically enabled and executed when the filter signal changes
177 * to a truthy value. When the filter signal changes back to a falsy value, the query will be disabled.
178 *
179 * **Reactive example**
180 * ```ts
181 * class ServiceOrComponent {
182 * filter = signal('')
183 *
184 * projectsQuery = injectInfiniteQuery(() => ({
185 * queryKey: ['projects', this.filter()],
186 * queryFn: ({ pageParam }) => fetchProjects(this.filter(), pageParam),
187 * initialPageParam: 0,
188 * getNextPageParam: (lastPage) => lastPage.nextCursor,
189 * enabled: !!this.filter(),
190 * }))
191 * }
192 * ```
193 * @param injectInfiniteQueryFn - A function that returns infinite query options.
194 * @param options - Additional configuration.
195 * @returns The infinite query result.
196 * @see https://tanstack.com/query/latest/docs/framework/angular/guides/infinite-queries
197 */
198export function injectInfiniteQuery<
199 TQueryFnData,
200 TError = DefaultError,
201 TData = InfiniteData<TQueryFnData>,
202 TQueryKey extends QueryKey = QueryKey,
203 TPageParam = unknown,
204>(
205 injectInfiniteQueryFn: () => ManualUndefinedInitialDataInfiniteOptions<
206 TQueryFnData,
207 TError,
208 TData,
209 TQueryKey,
210 TPageParam
211 >,
212 options?: InjectInfiniteQueryOptions,
213): CreateInfiniteQueryResult<TData, TError, TPageParam, InfiniteQueryMode>
214/**
215 * Injects an infinite query: a declarative dependency on an asynchronous source of data that is tied to a unique key.
216 * Infinite queries can additively "load more" data onto an existing set of data or "infinite scroll"
217 *
218 * **Basic example**
219 * ```ts
220 * class ServiceOrComponent {
221 * query = injectInfiniteQuery(() => ({
222 * queryKey: ['projects'],
223 * queryFn: ({ pageParam }) =>
224 * this.#http.get<Response>('/api/projects?cursor=' + pageParam),
225 * initialPageParam: 0,
226 * getNextPageParam: (lastPage) => lastPage.nextCursor,
227 * }))
228 * }
229 * ```
230 *
231 * Similar to `computed` from Angular, the function passed to `injectInfiniteQuery` will be run in the reactive context.
232 * In the example below, the query will be automatically enabled and executed when the filter signal changes
233 * to a truthy value. When the filter signal changes back to a falsy value, the query will be disabled.
234 *
235 * **Reactive example**
236 * ```ts
237 * class ServiceOrComponent {
238 * filter = signal('')
239 *
240 * projectsQuery = injectInfiniteQuery(() => ({
241 * queryKey: ['projects', this.filter()],
242 * queryFn: ({ pageParam }) => fetchProjects(this.filter(), pageParam),
243 * initialPageParam: 0,
244 * getNextPageParam: (lastPage) => lastPage.nextCursor,
245 * enabled: !!this.filter(),
246 * }))
247 * }
248 * ```
249 * @param injectInfiniteQueryFn - A function that returns infinite query options.
250 * @param options - Additional configuration.
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 injectInfiniteQueryFn: () => UndefinedInitialDataInfiniteOptions<
262 TQueryFnData,
263 TError,
264 TData,
265 TQueryKey,
266 TPageParam,
267 undefined
268 >,
269 options?: InjectInfiniteQueryOptions,
270): CreateInfiniteQueryResult<TData, TError, TPageParam, undefined>
271/**
272 * Injects an infinite query: a declarative dependency on an asynchronous source of data that is tied to a unique key.
273 * Infinite queries can additively "load more" data onto an existing set of data or "infinite scroll"
274 *
275 * **Basic example**
276 * ```ts
277 * class ServiceOrComponent {
278 * query = injectInfiniteQuery(() => ({
279 * queryKey: ['projects'],
280 * queryFn: ({ pageParam }) =>
281 * this.#http.get<Response>('/api/projects?cursor=' + pageParam),
282 * initialPageParam: 0,
283 * getNextPageParam: (lastPage) => lastPage.nextCursor,
284 * }))
285 * }
286 * ```
287 *
288 * Similar to `computed` from Angular, the function passed to `injectInfiniteQuery` will be run in the reactive context.
289 * In the example below, the query will be automatically enabled and executed when the filter signal changes
290 * to a truthy value. When the filter signal changes back to a falsy value, the query will be disabled.
291 *
292 * **Reactive example**
293 * ```ts
294 * class ServiceOrComponent {
295 * filter = signal('')
296 *
297 * projectsQuery = injectInfiniteQuery(() => ({
298 * queryKey: ['projects', this.filter()],
299 * queryFn: ({ pageParam }) => fetchProjects(this.filter(), pageParam),
300 * initialPageParam: 0,
301 * getNextPageParam: (lastPage) => lastPage.nextCursor,
302 * enabled: !!this.filter(),
303 * }))
304 * }
305 * ```
306 * @param injectInfiniteQueryFn - A function that returns infinite query options.
307 * @param options - Additional configuration.
308 * @returns The infinite query result.
309 * @see https://tanstack.com/query/latest/docs/framework/angular/guides/infinite-queries
310 */
311export function injectInfiniteQuery<
312 TQueryFnData,
313 TError = DefaultError,
314 TData = InfiniteData<TQueryFnData>,
315 TQueryKey extends QueryKey = QueryKey,
316 TPageParam = unknown,
317>(
318 injectInfiniteQueryFn: () => DefinedInitialDataInfiniteOptions<
319 TQueryFnData,
320 TError,
321 TData,
322 TQueryKey,
323 TPageParam
324 >,
325 options?: InjectInfiniteQueryOptions,
326): DefinedCreateInfiniteQueryResult<TData, TError, TPageParam>
327/**
328 * Injects an infinite query: a declarative dependency on an asynchronous source of data that is tied to a
329 * unique key. Infinite queries can additively "load more" data onto an existing set of data, or
330 * "infinite scroll".
331 * @param injectInfiniteQueryFn - A function returning the {@link UndefinedInitialDataInfiniteOptions} to use
332 * β€” everything you can pass to `injectInfiniteQuery`. Similar to `computed` from Angular, this function runs
333 * in the reactive context, so signals read inside it drive the query.
334 * @param options - Additional configuration.
335 * @returns The same signals as `injectQuery`, with the addition of `fetchNextPage`, `fetchPreviousPage`,
336 * `hasNextPage`, `hasPreviousPage`, `isFetchingNextPage`, and `isFetchingPreviousPage`. `data().pages` and
337 * `data().pageParams` are also added, as long as a `select` doesn't change `TData` away from its default
338 * `InfiniteData<TQueryFnData>` shape.
339 * @remarks Keep in mind that imperative fetch calls, such as `fetchNextPage`, may interfere with the default
340 * refetch behavior, resulting in outdated data. Make sure to call these functions only in response to user
341 * actions, or add conditions like `hasNextPage() && !isFetching()`. This is the only overload that accepts
342 * `queryFn: skipToken`, shown below.
343 * @see {@link infiniteQueryOptions} to share these options between `injectInfiniteQuery` and imperative APIs
344 * like `queryClient.fetchInfiniteQuery`.
345 * @example
346 * Fetching the next page from a button click:
347 * ```angular-ts
348 * @Component({
349 * selector: 'projects-list',
350 * template: `
351 * <ul>
352 * @for (page of projectsQuery.data()?.pages; track $index) {
353 * @for (project of page.projects; track project.id) {
354 * <li>{{ project.name }}</li>
355 * }
356 * }
357 * </ul>
358 * <button
359 * [disabled]="!projectsQuery.hasNextPage() || projectsQuery.isFetching()"
360 * (click)="projectsQuery.fetchNextPage()"
361 * >
362 * Load More
363 * </button>
364 * `,
365 * })
366 * export class ProjectsList {
367 * readonly projectsQuery = injectInfiniteQuery(() => ({
368 * queryKey: ['projects'],
369 * queryFn: ({ pageParam }) => fetchProjects(pageParam),
370 * initialPageParam: 0,
371 * getNextPageParam: (lastPage) => lastPage.nextId,
372 * }))
373 * }
374 * ```
375 * @example
376 * Fetching the next page automatically as the user scrolls, using an `IntersectionObserver` on a sentinel
377 * element after the list:
378 * ```angular-ts
379 * @Component({
380 * selector: 'projects-list',
381 * template: `
382 * <ul>
383 * @for (page of projectsQuery.data()?.pages; track $index) {
384 * @for (project of page.projects; track project.id) {
385 * <li>{{ project.name }}</li>
386 * }
387 * }
388 * </ul>
389 * <div #sentinel>{{ projectsQuery.isFetchingNextPage() ? 'Loading more...' : '' }}</div>
390 * `,
391 * })
392 * export class ProjectsList {
393 * readonly sentinel = viewChild<ElementRef<HTMLElement>>('sentinel')
394 *
395 * readonly projectsQuery = injectInfiniteQuery(() => ({
396 * queryKey: ['projects'],
397 * queryFn: ({ pageParam }) => fetchProjects(pageParam),
398 * initialPageParam: 0,
399 * getNextPageParam: (lastPage) => lastPage.nextId,
400 * }))
401 *
402 * constructor() {
403 * effect((onCleanup) => {
404 * const sentinel = this.sentinel()?.nativeElement
405 * if (
406 * sentinel == null ||
407 * !this.projectsQuery.hasNextPage() ||
408 * this.projectsQuery.isFetching()
409 * ) {
410 * return
411 * }
412 *
413 * const observer = new IntersectionObserver(([entry]) => {
414 * if (entry?.isIntersecting) this.projectsQuery.fetchNextPage()
415 * })
416 * observer.observe(sentinel)
417 *
418 * onCleanup(() => observer.disconnect())
419 * })
420 * }
421 * }
422 * ```
423 * @example
424 * A query that's disabled, type safe, until `postId` is set β€” pass `skipToken` as `queryFn` instead of
425 * setting `enabled: false`:
426 * ```angular-ts
427 * @Component({
428 * selector: 'comments',
429 * template: `
430 * @if (postId() == null) {
431 * Select a post
432 * } @else if (commentsQuery.isPending()) {
433 * Loading...
434 * } @else if (commentsQuery.isError()) {
435 * <span>Error: {{ commentsQuery.error()?.message }}</span>
436 * } @else {
437 * <ul>
438 * @for (page of commentsQuery.data().pages; track $index) {
439 * @for (comment of page.comments; track comment.id) {
440 * <li>{{ comment.text }}</li>
441 * }
442 * }
443 * </ul>
444 * }
445 * `,
446 * })
447 * export class Comments {
448 * readonly postId = signal<string | undefined>(undefined)
449 *
450 * readonly commentsQuery = injectInfiniteQuery(() => ({
451 * queryKey: ['post', this.postId(), 'comments'],
452 * queryFn:
453 * this.postId() != null
454 * ? ({ pageParam }) => fetchComments(this.postId()!, pageParam)
455 * : skipToken,
456 * initialPageParam: 0,
457 * getNextPageParam: (lastPage) => lastPage.nextId,
458 * }))
459 * }
460 * ```
461 */
462export function injectInfiniteQuery<
463 TQueryFnData,
464 TError = DefaultError,
465 TData = InfiniteData<TQueryFnData>,
466 TQueryKey extends QueryKey = QueryKey,
467 TPageParam = unknown,
468>(
469 injectInfiniteQueryFn: () => UndefinedInitialDataInfiniteOptions<
470 TQueryFnData,
471 TError,
472 TData,
473 TQueryKey,
474 TPageParam
475 >,
476 options?: InjectInfiniteQueryOptions,
477): CreateInfiniteQueryResult<TData, TError, TPageParam>
478/**
479 * This overload accepts the general {@link CreateInfiniteQueryOptions} shape rather than the
480 * `initialData`-aware overloads above, so whether `data` is defined can't be inferred from the call site β€”
481 * useful when wrapping `injectInfiniteQuery` in your own helper function that forwards caller-provided
482 * options.
483 * @param injectInfiniteQueryFn - A function that returns infinite query options. Similar to `computed` from
484 * Angular, this function runs in the reactive context, so signals read inside it drive the query.
485 * @param options - Additional configuration.
486 * @returns The infinite query result.
487 * @see https://tanstack.com/query/latest/docs/framework/angular/guides/infinite-queries
488 */
489export function injectInfiniteQuery<
490 TQueryFnData,
491 TError = DefaultError,
492 TData = InfiniteData<TQueryFnData>,
493 TQueryKey extends QueryKey = QueryKey,
494 TPageParam = unknown,
495>(
496 injectInfiniteQueryFn: () => CreateInfiniteQueryOptions<
497 TQueryFnData,
498 TError,
499 TData,
500 TQueryKey,
501 TPageParam
502 >,
503 options?: InjectInfiniteQueryOptions,
504): CreateInfiniteQueryResult<TData, TError, TPageParam>
505​
506export function injectInfiniteQuery(
507 injectInfiniteQueryFn: () => any,
508 options?: InjectInfiniteQueryOptions,
509) {
510 !options?.injector && assertInInjectionContext(injectInfiniteQuery)
511​
512 return runInInjectionContext(options?.injector ?? inject(Injector), () =>
513 createBaseQuery(injectInfiniteQueryFn, InfiniteQueryObserver),
514 )