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

inject-query.ts

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