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β
25export interface InjectInfiniteQueryOptions {
26 /**
27 * The `Injector` in which to create the infinite query.
28 *
29 * If this is not provided, the current injection context will be used instead (via `inject`).
30 */
31 injector?: Injector
32}
33β
34/**
35 * The options for `injectInfiniteQuery` are identical to `injectQuery`, with the addition of
36 * `initialPageParam`, `getNextPageParam`, `getPreviousPageParam`, and `maxPages`. Infinite queries can
37 * additively "load more" data onto an existing set of data, or "infinite scroll".
38 *
39 * This overload is selected when `initialData` is set on the options returned by `injectInfiniteQueryFn`,
40 * so the resulting `data` signal is never `undefined` (unless a `select` changes `TData` to include `undefined`).
41 *
42 * @remarks Keep in mind that imperative fetch calls, such as `fetchNextPage`, may interfere with the default
43 * refetch behavior, resulting in outdated data. Make sure to call these functions only in response to user
44 * actions, or add conditions like `hasNextPage() && !isFetching()`.
45 * @see {@link infiniteQueryOptions} to share these options between `injectInfiniteQuery` and imperative APIs
46 * like `queryClient.fetchInfiniteQuery`.
47 * @param injectInfiniteQueryFn - A function returning the {@link DefinedInitialDataInfiniteOptions} to use β
48 * everything you can pass to `injectInfiniteQuery`, with `initialData` set. Similar to `computed` from
49 * Angular, this function runs in the reactive context, so signals read inside it drive the 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 *
56 * @example
57 * ```angular-ts
58 * @Component({
59 * selector: 'projects',
60 * template: `
61 * <!-- `projectsQuery.data()` is never `undefined`, thanks to `initialData` β even if a
62 * refetch fails, so the list stays visible alongside the error. -->
63 * <ul>
64 * @for (page of projectsQuery.data().pages; track $index) {
65 * @for (project of page.projects; track project.id) {
66 * <li>{{ project.name }}</li>
67 * }
68 * }
69 * </ul>
70 * `,
71 * })
72 * export class Projects {
73 * readonly projectsQuery = injectInfiniteQuery(() => ({
74 * queryKey: ['projects'],
75 * queryFn: ({ pageParam }) => fetchProjects(pageParam),
76 * initialPageParam: 0,
77 * getNextPageParam: (lastPage) => lastPage.nextId,
78 * initialData: { pages: [], pageParams: [] },
79 * }))
80 * }
81 * ```
82 */
83export function injectInfiniteQuery<
84 TQueryFnData,
85 TError = DefaultError,
86 TData = InfiniteData<TQueryFnData>,
87 TQueryKey extends QueryKey = QueryKey,
88 TPageParam = unknown,
89>(
90 injectInfiniteQueryFn: () => DefinedInitialDataInfiniteOptions<
91 TQueryFnData,
92 TError,
93 TData,
94 TQueryKey,
95 TPageParam
96 >,
97 options?: InjectInfiniteQueryOptions,
98): DefinedCreateInfiniteQueryResult<TData, TError>
99β
100/**
101 * Injects an infinite query: a declarative dependency on an asynchronous source of data that is tied to a
102 * unique key. Infinite queries can additively "load more" data onto an existing set of data, or
103 * "infinite scroll".
104 *
105 * @remarks Keep in mind that imperative fetch calls, such as `fetchNextPage`, may interfere with the default
106 * refetch behavior, resulting in outdated data. Make sure to call these functions only in response to user
107 * actions, or add conditions like `hasNextPage() && !isFetching()`. This is the only overload that accepts
108 * `queryFn: skipToken`, shown below.
109 * @see {@link infiniteQueryOptions} to share these options between `injectInfiniteQuery` and imperative APIs
110 * like `queryClient.fetchInfiniteQuery`.
111 * @param injectInfiniteQueryFn - A function returning the {@link UndefinedInitialDataInfiniteOptions} to use
112 * β everything you can pass to `injectInfiniteQuery`. Similar to `computed` from Angular, this function runs
113 * in the reactive context, so signals read inside it drive the query.
114 * @param options - Additional configuration.
115 * @returns The same signals as `injectQuery`, with the addition of `fetchNextPage`, `fetchPreviousPage`,
116 * `hasNextPage`, `hasPreviousPage`, `isFetchingNextPage`, and `isFetchingPreviousPage`. `data().pages` and
117 * `data().pageParams` are also added, as long as a `select` doesn't change `TData` away from its default
118 * `InfiniteData<TQueryFnData>` shape.
119 *
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 *
151 * @example
152 * Fetching the next page automatically as the user scrolls, using an `IntersectionObserver` on a sentinel
153 * element after the list:
154 * ```angular-ts
155 * @Component({
156 * selector: 'projects-list',
157 * template: `
158 * <ul>
159 * @for (page of projectsQuery.data()?.pages; track $index) {
160 * @for (project of page.projects; track project.id) {
161 * <li>{{ project.name }}</li>
162 * }
163 * }
164 * </ul>
165 * <div #sentinel>{{ projectsQuery.isFetchingNextPage() ? 'Loading more...' : '' }}</div>
166 * `,
167 * })
168 * export class ProjectsList {
169 * readonly sentinel = viewChild<ElementRef<HTMLElement>>('sentinel')
170 *
171 * readonly projectsQuery = injectInfiniteQuery(() => ({
172 * queryKey: ['projects'],
173 * queryFn: ({ pageParam }) => fetchProjects(pageParam),
174 * initialPageParam: 0,
175 * getNextPageParam: (lastPage) => lastPage.nextId,
176 * }))
177 *
178 * constructor() {
179 * effect((onCleanup) => {
180 * const sentinel = this.sentinel()?.nativeElement
181 * if (
182 * sentinel == null ||
183 * !this.projectsQuery.hasNextPage() ||
184 * this.projectsQuery.isFetching()
185 * ) {
186 * return
187 * }
188 *
189 * const observer = new IntersectionObserver(([entry]) => {
190 * if (entry?.isIntersecting) this.projectsQuery.fetchNextPage()
191 * })
192 * observer.observe(sentinel)
193 *
194 * onCleanup(() => observer.disconnect())
195 * })
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 *
262 * @param injectInfiniteQueryFn - A function that returns infinite query options. Similar to `computed` from
263 * Angular, this function runs in the reactive context, so signals read inside it drive the query.
264 * @param options - Additional configuration.
265 * @returns The infinite query result.
266 */
267export function injectInfiniteQuery<
268 TQueryFnData,
269 TError = DefaultError,
270 TData = InfiniteData<TQueryFnData>,
271 TQueryKey extends QueryKey = QueryKey,
272 TPageParam = unknown,
273>(
274 injectInfiniteQueryFn: () => CreateInfiniteQueryOptions<
275 TQueryFnData,
276 TError,
277 TData,
278 TQueryKey,
279 TPageParam
280 >,
281 options?: InjectInfiniteQueryOptions,
282): CreateInfiniteQueryResult<TData, TError>
283β
284export function injectInfiniteQuery(
285 injectInfiniteQueryFn: () => CreateInfiniteQueryOptions,
286 options?: InjectInfiniteQueryOptions,
287) {
288 !options?.injector && assertInInjectionContext(injectInfiniteQuery)
289 const injector = options?.injector ?? inject(Injector)
290 return runInInjectionContext(injector, () =>
291 createBaseQuery(
292 injectInfiniteQueryFn,
293 InfiniteQueryObserver as typeof QueryObserver,
294 ),
295 )
296}