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

inject-query.ts

205 lines6.9 KB

1import { QueryObserver } 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 { DefaultError, QueryKey } from '@tanstack/query-core'
10import type {
11 CreateQueryOptions,
12 CreateQueryResult,
13 DefinedCreateQueryResult,
14} from './types'
15import type {
16 DefinedInitialDataOptions,
17 UndefinedInitialDataOptions,
18} from './query-options'
19​
20/**
21 * Options for `injectQuery`, passed after the function that returns the query options.
22 */
23export interface InjectQueryOptions {
24 /**
25 * The `Injector` in which to create the query.
26 *
27 * If this is not provided, the current injection context will be used instead (via `inject`).
28 */
29 injector?: Injector
31​
32/**
33 * This overload is selected when `initialData` is set on the options returned by `injectQueryFn`, so the
34 * resulting `data` signal is never `undefined` (unless a `select` changes `TData` to include `undefined`).
35 * @param injectQueryFn - A function returning the {@link DefinedInitialDataOptions} to use β€” everything you
36 * can pass to `injectQuery`, with `initialData` set. Similar to `computed` from Angular, this function runs
37 * in the reactive context, so signals read inside it (in `queryKey`, `enabled`, etc.) drive the query.
38 * @param options - Additional configuration
39 * @returns The query result, typed so that `data` is never `undefined` (unless a `select` changes `TData` to
40 * include `undefined`).
41 * @see https://tanstack.com/query/latest/docs/framework/angular/guides/queries
42 * @see {@link queryOptions} to share these options between `injectQuery` and imperative APIs like
43 * `queryClient.fetchQuery`.
44 * @example
45 * ```angular-ts
46 * @Component({
47 * selector: 'posts',
48 * template: `
49 * <!-- `postsQuery.data()` is `Post[]`, never `undefined`, thanks to `initialData` β€” even if a
50 * refetch fails, so the list stays visible alongside the error. -->
51 * @if (postsQuery.isError()) {
52 * <span>Error: {{ postsQuery.error()?.message }}</span>
53 * }
54 * <ul>
55 * @for (post of postsQuery.data(); track post.id) {
56 * <li>{{ post.title }}</li>
57 * }
58 * </ul>
59 * `,
60 * })
61 * export class Posts {
62 * readonly postsQuery = injectQuery(() => ({
63 * queryKey: ['posts'],
64 * queryFn: fetchPosts,
65 * initialData: [],
66 * }))
67 * }
68 * ```
69 */
70export function injectQuery<
71 TQueryFnData = unknown,
72 TError = DefaultError,
73 TData = TQueryFnData,
74 TQueryKey extends QueryKey = QueryKey,
75>(
76 injectQueryFn: () => DefinedInitialDataOptions<
77 TQueryFnData,
78 TError,
79 TData,
80 TQueryKey
81 >,
82 options?: InjectQueryOptions,
83): DefinedCreateQueryResult<TData, TError>
84​
85/**
86 * Injects a query: a declarative dependency on an asynchronous source of data that is tied to a unique key.
87 * @param injectQueryFn - A function returning the {@link UndefinedInitialDataOptions} to use β€” everything
88 * you can pass to `injectQuery`. Similar to `computed` from Angular, this function runs in the reactive
89 * context, so signals read inside it (in `queryKey`, `enabled`, etc.) drive the query.
90 * @param options - Additional configuration
91 * @returns The query result. `status()` is `'pending'` if there is no cached data to display, `'error'` if
92 * the last fetch attempt failed, or `'success'` if the query has data to display. `isPending`/`isSuccess`/
93 * `isError` are type-guard methods for convenience.
94 * @see https://tanstack.com/query/latest/docs/framework/angular/guides/queries
95 * @see {@link queryOptions} to share these options between `injectQuery` and imperative APIs like
96 * `queryClient.fetchQuery`.
97 * @example
98 * ```angular-ts
99 * @Component({
100 * selector: 'posts',
101 * template: `
102 * @if (postsQuery.isPending()) {
103 * Loading...
104 * } @else if (postsQuery.isError()) {
105 * <span>Error: {{ postsQuery.error()?.message }}</span>
106 * } @else {
107 * <ul>
108 * @for (post of postsQuery.data(); track post.id) {
109 * <li>{{ post.title }}</li>
110 * }
111 * </ul>
112 * }
113 * `,
114 * })
115 * export class Posts {
116 * readonly postsQuery = injectQuery(() => ({
117 * queryKey: ['posts'],
118 * queryFn: fetchPosts,
119 * }))
120 * }
121 * ```
122 * @example
123 * Similar to `computed` from Angular, the function passed to `injectQuery` runs in the reactive context. In
124 * the example below, the query is automatically enabled and executed when the filter signal changes to a
125 * truthy value. When the filter signal changes back to a falsy value, the query is disabled.
126 * ```angular-ts
127 * @Component({
128 * selector: 'posts',
129 * template: `
130 * <input [ngModel]="filter()" (ngModelChange)="filter.set($event)" />
131 * @if (postsQuery.isPending()) {
132 * Loading...
133 * } @else if (postsQuery.isError()) {
134 * <span>Error: {{ postsQuery.error()?.message }}</span>
135 * } @else {
136 * <ul>
137 * @for (post of postsQuery.data(); track post.id) {
138 * <li>{{ post.title }}</li>
139 * }
140 * </ul>
141 * }
142 * `,
143 * })
144 * export class Posts {
145 * readonly filter = signal('')
146 *
147 * readonly postsQuery = injectQuery(() => ({
148 * queryKey: ['posts', this.filter()],
149 * queryFn: () => fetchPosts(this.filter()),
150 * // Signals can be combined with expressions
151 * enabled: !!this.filter(),
152 * }))
153 * }
154 * ```
155 */
156export function injectQuery<
157 TQueryFnData = unknown,
158 TError = DefaultError,
159 TData = TQueryFnData,
160 TQueryKey extends QueryKey = QueryKey,
161>(
162 injectQueryFn: () => UndefinedInitialDataOptions<
163 TQueryFnData,
164 TError,
165 TData,
166 TQueryKey
167 >,
168 options?: InjectQueryOptions,
169): CreateQueryResult<TData, TError>
170​
171/**
172 * This overload accepts the general {@link CreateQueryOptions} shape rather than the `initialData`-aware
173 * overloads above, so whether `data` is defined can't be inferred from the call site β€” useful when wrapping
174 * `injectQuery` in your own helper function that forwards caller-provided options.
175 * @param injectQueryFn - A function that returns query options. Similar to `computed` from Angular, this
176 * function runs in the reactive context, so signals read inside it (in `queryKey`, `enabled`, etc.) drive
177 * the query.
178 * @param options - Additional configuration
179 * @returns The query result.
180 * @see https://tanstack.com/query/latest/docs/framework/angular/guides/queries
181 */
182export function injectQuery<
183 TQueryFnData = unknown,
184 TError = DefaultError,
185 TData = TQueryFnData,
186 TQueryKey extends QueryKey = QueryKey,
187>(
188 injectQueryFn: () => CreateQueryOptions<
189 TQueryFnData,
190 TError,
191 TData,
192 TQueryKey
193 >,
194 options?: InjectQueryOptions,
195): CreateQueryResult<TData, TError>
196​
197export function injectQuery(
198 injectQueryFn: () => CreateQueryOptions,
199 options?: InjectQueryOptions,
200) {
201 !options?.injector && assertInInjectionContext(injectQuery)
202 return runInInjectionContext(options?.injector ?? inject(Injector), () =>
203 createBaseQuery(injectQueryFn, QueryObserver),
204 ) as unknown as CreateQueryResult