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