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

inject-queries.ts

297 lines9.5 KB

1import {
2 assertInInjectionContext,
3 computed,
4 effect,
5 inject,
6 untracked,
7} from '@angular/core'
8import { QueriesObserver, QueryClient } from '@tanstack/query-core'
9import { injectIsRestoring } from './inject-is-restoring'
10import { injectExternalStore } from './utils/inject-external-store'
11import { injectPendingTasksLifecycle } from './utils/inject-pending-tasks-lifecycle'
12import { injectQueryZone } from './utils/inject-query-zone'
13import { queryResultFields } from './utils/result-fields'
14import { signalProxy } from './utils/signal-proxy'
15import type { Signal } from '@angular/core'
16import type {
17 QueryObserverOptions,
18 QueryObserverResult,
19} from '@tanstack/query-core'
20import type {
21 InjectQueriesOptions,
22 QueriesResults,
23} from './inject-queries.types'
24​
25/**
26 * Injects a signal to fetch a variable number of queries.
27 *
28 * The `queries` key accepts an array with query option objects mostly identical to `injectQuery`'s. Having
29 * the same query key more than once in the array of query objects may cause some data to be shared between
30 * queries. To avoid this, consider de-duplicating the queries and map the results back to the desired
31 * structure.
32 *
33 * The `combine` option can be used to combine the results of the queries into a single value.
34 * @param optionsFn - A function returning the queries' options β€” an array of query option objects under
35 * `queries`, and an optional `combine`. Similar to `computed` from Angular, this function runs in the
36 * reactive context, so signals read inside it (e.g. to build the `queries` array) drive the queries.
37 * @returns A `Signal` with the combined result. Without `combine`, this is an array with all the query
38 * results, in the same order as the input. When `combine` is provided, this is the value returned by
39 * `combine` instead.
40 * @remarks Unlike `injectQuery`, `injectQueries` cannot infer the `data` argument of an _inline_ `select`
41 * from its sibling `queryFn`. Because `injectQueries` infers the type of the whole `queries` array at once,
42 * the `select` parameter of a query object written inline cannot be contextually typed from that same
43 * object's `queryFn`, so it falls back to `unknown` β€” a
44 * [known TypeScript limitation](https://github.com/TanStack/query/issues/6556). Annotate the `select`
45 * parameter explicitly, or define the query with {@link queryOptions}, which resolves its types in a single
46 * object _before_ it reaches `injectQueries`, to work around this β€” see the example below.
47 * @see https://tanstack.com/query/latest/docs/framework/angular/guides/parallel-queries
48 * @example
49 * ```angular-ts
50 * @Component({
51 * selector: 'posts',
52 * template: `
53 * <ul>
54 * @for (query of postQueries(); track $index) {
55 * @if (query.isPending()) {
56 * <li>Loading...</li>
57 * } @else if (query.isError()) {
58 * <li>Error: {{ query.error()?.message }}</li>
59 * } @else {
60 * <li>{{ query.data().title }}</li>
61 * }
62 * }
63 * </ul>
64 * `,
65 * })
66 * export class Posts {
67 * readonly ids = signal([1, 2, 3])
68 *
69 * readonly postQueries = injectQueries(() => ({
70 * queries: this.ids().map((id) => ({
71 * queryKey: ['post', id],
72 * queryFn: () => fetchPost(id),
73 * staleTime: Infinity,
74 * })),
75 * }))
76 * }
77 * ```
78 * @example
79 * Combining results into a single value:
80 * ```angular-ts
81 * @Component({
82 * selector: 'posts',
83 * template: `
84 * @if (combined().isPending) {
85 * Loading...
86 * } @else if (combined().isError) {
87 * Error loading posts
88 * } @else {
89 * <ul>
90 * @for (post of combined().data; track post?.id) {
91 * <li>{{ post?.title }}</li>
92 * }
93 * </ul>
94 * }
95 * `,
96 * })
97 * export class Posts {
98 * readonly ids = signal([1, 2, 3])
99 *
100 * readonly combined = injectQueries(() => ({
101 * queries: this.ids().map((id) => ({
102 * queryKey: ['post', id],
103 * queryFn: () => fetchPost(id),
104 * })),
105 * combine: (postQueries) => ({
106 * data: postQueries.map((query) => query.data),
107 * isPending: postQueries.some((query) => query.isPending),
108 * isError: postQueries.some((query) => query.isError),
109 * }),
110 * }))
111 * }
112 * ```
113 * @example
114 * Typing `select` via {@link queryOptions}. Note that spreading a `queryOptions` result and overriding
115 * `select` inline still falls back to `unknown` β€” wrap the spread in `queryOptions` again so the override is
116 * resolved before it reaches `injectQueries`:
117 * ```angular-ts
118 * const postOptions = (id: number) =>
119 * queryOptions({
120 * queryKey: ['post', id],
121 * queryFn: () => fetchPost(id),
122 * })
123 *
124 * @Component({
125 * selector: 'post-title',
126 * template: `<h1>{{ fixed()[0].data() }}</h1>`,
127 * })
128 * export class PostTitle {
129 * readonly id = signal(1)
130 *
131 * readonly broken = injectQueries(() => ({
132 * queries: [
133 * {
134 * ...postOptions(this.id()),
135 * // ❌ `data` is `unknown` here
136 * select: (data) => data.title,
137 * },
138 * ],
139 * }))
140 *
141 * readonly fixed = injectQueries(() => ({
142 * queries: [
143 * queryOptions({
144 * ...postOptions(this.id()),
145 * // βœ… `data` is `Post`
146 * select: (data) => data.title,
147 * }),
148 * ],
149 * }))
150 * }
151 * ```
152 */
153export function injectQueries<
154 T extends Array<any>,
155 TCombinedResult = QueriesResults<T>,
156>(
157 optionsFn: () => InjectQueriesOptions<T, TCombinedResult>,
158): Signal<TCombinedResult> {
159 if (typeof ngDevMode === 'undefined' || ngDevMode) {
160 assertInInjectionContext(injectQueries)
161 }
162 const outsideZone = injectQueryZone()
163 const queryClient = inject(QueryClient)
164 const isRestoring = injectIsRestoring()
165 const lifecycle = injectPendingTasksLifecycle()
166​
167 const optionsSignal = computed(optionsFn)
168​
169 const defaultedQueries = computed(() => {
170 return optionsSignal().queries.map((opts) => {
171 const defaultedOptions = queryClient.defaultQueryOptions(
172 opts as QueryObserverOptions,
173 )
174 defaultedOptions._optimisticResults = isRestoring()
175 ? 'isRestoring'
176 : 'optimistic'
177 defaultedOptions.notifyOnChangeProps = 'all'
178​
179 return defaultedOptions
180 })
181 })
182​
183 const shouldBlockPendingTasks = (
184 observer: QueriesObserver<TCombinedResult>,
185 results: Array<QueryObserverResult>,
186 ) => {
187 const queries = observer.getQueries()
188​
189 return results.some((result, index) => {
190 return (
191 queries[index]?.state.fetchStatus !== 'idle' ||
192 (result.fetchStatus !== 'idle' && result.isEnabled)
193 )
194 })
195 }
196​
197 const observerSignal = computed(
198 () =>
199 new QueriesObserver<TCombinedResult>(
200 queryClient,
201 untracked(defaultedQueries),
202 ),
203 )
204​
205 effect(() => {
206 const queries = defaultedQueries()
207 outsideZone(() => untracked(() => observerSignal().setQueries(queries)))
208 })
209​
210 // Methods address the current array slot, including methods handed to combine.
211 const refetches: Array<QueryObserverResult['refetch']> = []
212 const getRefetch = (index: number): QueryObserverResult['refetch'] =>
213 (refetches[index] ??= (options) =>
214 outsideZone(() =>
215 untracked(() => {
216 const observer = observerSignal()
217 observer.setQueries(defaultedQueries())
218 const queryObserver = observer.getObservers()[index]
219 if (!queryObserver) {
220 return Promise.reject(
221 new Error(`Cannot refetch removed query at index ${index}`),
222 )
223 }
224 return queryObserver.refetch(options)
225 }),
226 ))
227​
228 const resultSignal = injectExternalStore(() => {
229 const observer = observerSignal()
230 const restoring = isRestoring()
231 return {
232 getSnapshot: () => {
233 const results = observer.getOptimisticResult(
234 defaultedQueries(),
235 undefined,
236 )[0]
237 refetches.length = results.length
238 return results.map((result, index) => ({
239 ...result,
240 refetch: getRefetch(index),
241 }))
242 },
243 subscribe: restoring
244 ? undefined
245 : (onStoreChange) => {
246 const unsubscribe = observer.subscribe(() => {
247 if (lifecycle.destroyed) return
248 onStoreChange()
249 })
250 return () => {
251 lifecycle.setPending(false)
252 unsubscribe()
253 }
254 },
255 }
256 })
257​
258 effect((onCleanup) => {
259 const results = resultSignal()
260 if (isRestoring()) {
261 lifecycle.setPending(false)
262 return
263 }
264​
265 lifecycle.setPending(shouldBlockPendingTasks(observerSignal(), results))
266 onCleanup(() => lifecycle.setPending(false))
267 })
268​
269 const createResultProxy = (index: number) => {
270 const resultAtIndexSignal = computed(() => resultSignal()[index]!)
271 return Object.assign(signalProxy(resultAtIndexSignal, queryResultFields), {
272 refetch: getRefetch(index),
273 })
274 }
275​
276 const resultProxies: Array<ReturnType<typeof createResultProxy>> = []
277 const proxiedResultsSignal = computed(() => {
278 const results = resultSignal()
279 resultProxies.length = results.length
280​
281 return results.map((_, index) => {
282 return (resultProxies[index] ??= createResultProxy(index))
283 })
284 })
285​
286 // Combine in Angular's tracked computation. Core must notify for every raw
287 // result change, including changes a previous combine function ignored.
288 return computed(() => {
289 const result = resultSignal()
290 const { combine } = optionsSignal()
291​
292 if (combine)
293 return combine(result as Parameters<NonNullable<typeof combine>>[0])
294​
295 return proxiedResultsSignal() as unknown as TCombinedResult
296 })