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