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