Open History to see the last commit
1import type {
2 DefaultError,
3 InitialDataFunction,
4 NonUndefinedGuard,
5 OmitKeyof,
6 QueryKey,
7 QueryKeyWithDataTag,
8 SkipToken,
9} from '@tanstack/query-core'
10import type { CreateQueryOptions } from './types'
11β
12/**
13 * The options accepted by the `queryOptions` overload selected when `initialData` is omitted, may be
14 * `undefined`, or is a function that may return `undefined` β `data` may be `undefined` while the query is
15 * `pending`.
16 * @template TQueryFnData - The type your `queryFn` resolves to.
17 * @template TError - The type of errors your `queryFn` may throw.
18 * @template TData - The type `data` ends up as after `select` runs.
19 * @template TQueryKey - The type of your `queryKey`.
20 */
21export type UndefinedInitialDataOptions<
22 TQueryFnData = unknown,
23 TError = DefaultError,
24 TData = TQueryFnData,
25 TQueryKey extends QueryKey = QueryKey,
26> = CreateQueryOptions<TQueryFnData, TError, TData, TQueryKey> & {
27 /**
28 * If set, this value will be used as the initial data for the query cache (as long as the query hasn't been
29 * created or cached yet). If set to a function, the function will be called **once** during the shared/root
30 * query initialization, and be expected to synchronously return the initial data. Initial data is
31 * considered stale by default unless a `staleTime` has been set. `initialData` **is persisted** to the
32 * cache.
33 */
34 initialData?:
35 | undefined
36 | InitialDataFunction<NonUndefinedGuard<TQueryFnData>>
37 | NonUndefinedGuard<TQueryFnData>
38}
39β
40/**
41 * The options accepted by the `queryOptions` overload selected when `queryFn` is not `skipToken` and
42 * `initialData` is omitted, may be `undefined`, or is a function that may return `undefined` β same as
43 * {@link UndefinedInitialDataOptions}, but `queryFn` may not be `skipToken`.
44 * @template TQueryFnData - The type your `queryFn` resolves to.
45 * @template TError - The type of errors your `queryFn` may throw.
46 * @template TData - The type `data` ends up as after `select` runs.
47 * @template TQueryKey - The type of your `queryKey`.
48 */
49export type UnusedSkipTokenOptions<
50 TQueryFnData = unknown,
51 TError = DefaultError,
52 TData = TQueryFnData,
53 TQueryKey extends QueryKey = QueryKey,
54> = OmitKeyof<
55 CreateQueryOptions<TQueryFnData, TError, TData, TQueryKey>,
56 'queryFn'
57> & {
58 /**
59 * `skipToken` is not allowed as a value here β this overload is selected when `initialData` is omitted, may
60 * be `undefined`, or is a function that may return `undefined`. If you don't intend to run the query yet,
61 * set `enabled: false` β omitting `queryFn` alone still triggers a fetch that fails with "Missing queryFn"
62 * unless `enabled` is `false` or a default query function has been defined. A default query function only
63 * supplies `queryFn`; it doesn't defer the fetch on its own.
64 */
65 queryFn?: Exclude<
66 CreateQueryOptions<TQueryFnData, TError, TData, TQueryKey>['queryFn'],
67 SkipToken | undefined
68 >
69}
70β
71/**
72 * The options accepted by the `queryOptions` overload selected when `initialData` is known to be defined β
73 * `data` is never `undefined` (unless a `select` changes `TData` to include `undefined`).
74 * @template TQueryFnData - The type your `queryFn` resolves to.
75 * @template TError - The type of errors your `queryFn` may throw.
76 * @template TData - The type `data` ends up as after `select` runs.
77 * @template TQueryKey - The type of your `queryKey`.
78 */
79export type DefinedInitialDataOptions<
80 TQueryFnData = unknown,
81 TError = DefaultError,
82 TData = TQueryFnData,
83 TQueryKey extends QueryKey = QueryKey,
84> = CreateQueryOptions<TQueryFnData, TError, TData, TQueryKey> & {
85 /**
86 * If set, this value will be used as the initial data for the query cache (as long as the query hasn't been
87 * created or cached yet). If set to a function, the function will be called **once** during the shared/root
88 * query initialization, and be expected to synchronously return the initial data. Initial data is
89 * considered stale by default unless a `staleTime` has been set. `initialData` **is persisted** to the
90 * cache.
91 */
92 initialData:
93 | NonUndefinedGuard<TQueryFnData>
94 | (() => NonUndefinedGuard<TQueryFnData>)
95}
96β
97/**
98 * You can generally pass everything to `queryOptions` that you can also pass to `injectQuery`. These options
99 * can be shared across functions and imperative APIs such as `queryClient.query`. `options.queryKey` is
100 * required and is the query key to generate options for.
101 *
102 * This overload is selected when `initialData` is known to be defined, so the resulting `data` is never
103 * `undefined` (unless a `select` changes `TData` to include `undefined`).
104 * @param options - The {@link DefinedInitialDataOptions} to use β everything you can pass to `injectQuery`,
105 * with `initialData` known to be defined.
106 * @returns The same options object, typed so that `queryKey` carries the inferred data type.
107 * @see {@link injectQuery} to run a query with these options.
108 * @see [The Query Options API](https://tkdodo.eu/blog/the-query-options-api) for more on this pattern.
109 * @example
110 * ```angular-ts
111 * import { queryOptions, injectQuery } from '@tanstack/angular-query'
112 *
113 * export const postsOptions = queryOptions({
114 * queryKey: ['posts'],
115 * queryFn: fetchPosts,
116 * initialData: [],
117 * })
118 *
119 * @Component({
120 * selector: 'posts',
121 * template: `
122 * <!-- `postsQuery.data()` is never `undefined`, thanks to `initialData` β even if a refetch
123 * fails, so the list stays visible alongside the error. -->
124 * @if (postsQuery.isError()) {
125 * <span>Error: {{ postsQuery.error()?.message }}</span>
126 * }
127 * <ul>
128 * @for (post of postsQuery.data(); track post.id) {
129 * <li>{{ post.title }}</li>
130 * }
131 * </ul>
132 * `,
133 * })
134 * export class Posts {
135 * readonly postsQuery = injectQuery(() => postsOptions)
136 * }
137 * ```
138 */
139export function queryOptions<
140 TQueryFnData = unknown,
141 TError = DefaultError,
142 TData = TQueryFnData,
143 TQueryKey extends QueryKey = QueryKey,
144>(
145 options: DefinedInitialDataOptions<TQueryFnData, TError, TData, TQueryKey>,
146): DefinedInitialDataOptions<TQueryFnData, TError, TData, TQueryKey> &
147 QueryKeyWithDataTag<TQueryKey, TQueryFnData, TError>
148β
149/**
150 * You can generally pass everything to `queryOptions` that you can also pass to `injectQuery`. These options
151 * can be shared across functions and imperative APIs such as `queryClient.query`. `options.queryKey` is
152 * required and is the query key to generate options for.
153 * @param options - The {@link UnusedSkipTokenOptions} to use β everything you can pass to `injectQuery`.
154 * @returns The same options object, typed so that `queryKey` carries the inferred data type.
155 * @see {@link injectQuery} to run a query with these options.
156 * @see [The Query Options API](https://tkdodo.eu/blog/the-query-options-api) for more on this pattern.
157 * @example
158 * A parameterized factory, so the same options object can be reused per `id`:
159 * ```angular-ts
160 * import { queryOptions, injectQuery } from '@tanstack/angular-query'
161 *
162 * export const postOptions = (id: string) =>
163 * queryOptions({
164 * queryKey: ['post', id],
165 * queryFn: () => fetchPost(id),
166 * })
167 *
168 * @Component({
169 * selector: 'post',
170 * template: `
171 * @if (postQuery.isPending()) {
172 * Loading...
173 * } @else if (postQuery.isError()) {
174 * <span>Error: {{ postQuery.error()?.message }}</span>
175 * } @else {
176 * <h1>{{ postQuery.data().title }}</h1>
177 * }
178 * `,
179 * })
180 * export class Post {
181 * readonly id = signal('1')
182 * readonly postQuery = injectQuery(() => postOptions(this.id()))
183 * }
184 * ```
185 */
186export function queryOptions<
187 TQueryFnData = unknown,
188 TError = DefaultError,
189 TData = TQueryFnData,
190 TQueryKey extends QueryKey = QueryKey,
191>(
192 options: UnusedSkipTokenOptions<TQueryFnData, TError, TData, TQueryKey>,
193): UnusedSkipTokenOptions<TQueryFnData, TError, TData, TQueryKey> &
194 QueryKeyWithDataTag<TQueryKey, TQueryFnData, TError>
195β
196/**
197 * You can generally pass everything to `queryOptions` that you can also pass to `injectQuery`. These options
198 * can be shared across functions and imperative APIs such as `queryClient.query`. `options.queryKey` is
199 * required and is the query key to generate options for.
200 * @param options - The {@link UndefinedInitialDataOptions} to use β everything you can pass to `injectQuery`.
201 * @returns The same options object, typed so that `queryKey` carries the inferred data type.
202 * @remarks This is the only overload that accepts `queryFn: skipToken`, shown below.
203 * @see {@link injectQuery} to run a query with these options.
204 * @see [The Query Options API](https://tkdodo.eu/blog/the-query-options-api) for more on this pattern.
205 * @example
206 * A parameterized factory, so the same options object can be reused per `id`:
207 * ```angular-ts
208 * import { queryOptions, injectQuery } from '@tanstack/angular-query'
209 *
210 * export const postOptions = (id: string) =>
211 * queryOptions({
212 * queryKey: ['post', id],
213 * queryFn: () => fetchPost(id),
214 * })
215 *
216 * @Component({
217 * selector: 'post',
218 * template: `
219 * @if (postQuery.isPending()) {
220 * Loading...
221 * } @else if (postQuery.isError()) {
222 * <span>Error: {{ postQuery.error()?.message }}</span>
223 * } @else {
224 * <h1>{{ postQuery.data().title }}</h1>
225 * }
226 * `,
227 * })
228 * export class Post {
229 * readonly id = signal('1')
230 * readonly postQuery = injectQuery(() => postOptions(this.id()))
231 * }
232 * ```
233 * @example
234 * A factory that disables the query, type safe, until `postId` is set:
235 * ```angular-ts
236 * import { queryOptions, skipToken, injectQuery } from '@tanstack/angular-query'
237 *
238 * export const postOptions = (postId: number | undefined) =>
239 * queryOptions({
240 * queryKey: ['post', postId],
241 * queryFn: postId != null ? () => fetchPost(postId) : skipToken,
242 * })
243 *
244 * @Component({
245 * selector: 'post',
246 * template: `
247 * @if (postId() == null) {
248 * Select a post
249 * } @else if (postQuery.isPending()) {
250 * Loading...
251 * } @else if (postQuery.isError()) {
252 * <span>Error: {{ postQuery.error()?.message }}</span>
253 * } @else {
254 * <h1>{{ postQuery.data().title }}</h1>
255 * }
256 * `,
257 * })
258 * export class Post {
259 * readonly postId = signal<number | undefined>(undefined)
260 * readonly postQuery = injectQuery(() => postOptions(this.postId()))
261 * }
262 * ```
263 */
264export function queryOptions<
265 TQueryFnData = unknown,
266 TError = DefaultError,
267 TData = TQueryFnData,
268 TQueryKey extends QueryKey = QueryKey,
269>(
270 options: UndefinedInitialDataOptions<TQueryFnData, TError, TData, TQueryKey>,
271): UndefinedInitialDataOptions<TQueryFnData, TError, TData, TQueryKey> &
272 QueryKeyWithDataTag<TQueryKey, TQueryFnData, TError>
273β
274export function queryOptions(options: unknown) {
275 return options
276}