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