Open History to see the last commit
1import type {
2 DeepUnwrapRef,
3 MaybeRef,
4 MaybeRefDeep,
5 MaybeRefOrGetter,
6 ShallowOption,
7} from './types'
8import type {
9 DefaultError,
10 InitialDataFunction,
11 NonUndefinedGuard,
12 QueryBooleanOption,
13 QueryKey,
14 QueryKeyWithDataTag,
15 QueryObserverOptions,
16} from '@tanstack/query-core'
17β
18/**
19 * The plain, unwrapped options that `queryOptions` hands back, and what `useQuery`, `useQueries`, and the
20 * `queryClient` methods see once `ref`s have been resolved. To pass options in, use
21 * {@link UseQueryOptions}, which accepts the same options as `ref`s and `computed`s too.
22 * @template TQueryFnData - The type your `queryFn` resolves to.
23 * @template TError - The type of errors your `queryFn` may throw.
24 * @template TData - The type `data` ends up as after `select` runs.
25 * @template TQueryData - The type of data stored in the cache, before `select` runs. Defaults to
26 * `TQueryFnData` and can be configured independently of it.
27 * @template TQueryKey - The type of your `queryKey`.
28 */
29export type QueryOptions<
30 TQueryFnData = unknown,
31 TError = DefaultError,
32 TData = TQueryFnData,
33 TQueryData = TQueryFnData,
34 TQueryKey extends QueryKey = QueryKey,
35> = {
36 [
37 Property in keyof QueryObserverOptions<
38 TQueryFnData,
39 TError,
40 TData,
41 TQueryData,
42 TQueryKey
43 >
44 ]: Property extends 'enabled'
45 ?
46 | MaybeRefOrGetter<boolean | undefined>
47 | (() => QueryBooleanOption<
48 TQueryFnData,
49 TError,
50 TQueryData,
51 DeepUnwrapRef<TQueryKey>
52 >)
53 : Property extends 'queryKey'
54 ? MaybeRefOrGetter<TQueryKey>
55 : QueryObserverOptions<
56 TQueryFnData,
57 TError,
58 TData,
59 TQueryData,
60 DeepUnwrapRef<TQueryKey>
61 >[Property]
62} & ShallowOption
63β
64// Widen the type of the symbol to enable type inference even if skipToken is not immutable.
65type SkipTokenForUseQuery = symbol
66β
67/**
68 * The options accepted by `queryOptions`, `useQuery`, and the other query hooks. `enabled` tracks reactive
69 * dependencies automatically as a `ref`, a plain value, or a reactive getter (`() => ...`). `queryKey` reacts
70 * through a `ref` or a reactive getter for the array itself, or `ref`s and reactive getters as individual
71 * entries. Other options are read once when passed as a plain value, and stay reactive when passed as a `ref`
72 * or a `computed`. Only `enabled` and `queryKey` read a function as a getter, so `queryFn` reacts through a
73 * `computed`: a function there is the query function itself.
74 *
75 * If you instead pass a getter for the whole options object (`useQuery(() => ({ ... }))`), every option
76 * inside it β including `staleTime`, `retry`, and `select` β is re-evaluated whenever the getter's own
77 * reactive dependencies change, since the entire object is recomputed.
78 *
79 * `select` only re-runs when `data` changes, or when the `select` function's own reference changes. Since a
80 * Vue `setup()` function runs only once per component instance, an inline `select` function passed directly
81 * to `queryOptions`/`useQuery` already has a stable reference across reactive updates. An inline `select`
82 * created inside a whole-options getter is recreated β and so can change reference β every time that getter
83 * re-evaluates.
84 * @template TQueryFnData - The type your `queryFn` resolves to.
85 * @template TError - The type of errors your `queryFn` may throw.
86 * @template TData - The type `data` ends up as after `select` runs.
87 * @template TQueryData - The type of data stored in the cache, before `select` runs. Defaults to
88 * `TQueryFnData` and can be configured independently of it.
89 * @template TQueryKey - The type of your `queryKey`.
90 */
91export type UseQueryOptions<
92 TQueryFnData = unknown,
93 TError = DefaultError,
94 TData = TQueryFnData,
95 TQueryData = TQueryFnData,
96 TQueryKey extends QueryKey = QueryKey,
97> = MaybeRef<
98 {
99 [
100 Property in keyof QueryObserverOptions<
101 TQueryFnData,
102 TError,
103 TData,
104 TQueryData,
105 TQueryKey
106 >
107 ]: Property extends 'enabled' | 'queryKey'
108 ? QueryOptions<
109 TQueryFnData,
110 TError,
111 TData,
112 TQueryData,
113 TQueryKey
114 >[Property]
115 : Property extends 'queryFn'
116 ? MaybeRefDeep<
117 | QueryOptions<
118 TQueryFnData,
119 TError,
120 TData,
121 TQueryData,
122 TQueryKey
123 >[Property]
124 | SkipTokenForUseQuery
125 >
126 : MaybeRefDeep<
127 QueryOptions<
128 TQueryFnData,
129 TError,
130 TData,
131 TQueryData,
132 TQueryKey
133 >[Property]
134 >
135 } & ShallowOption
136>
137β
138type WithUndefinedInitialData<TQueryFnData> = {
139 /**
140 * If set, this value will be used as the initial data for the query cache (as long as the query hasn't been
141 * created or cached yet). If set to a function, the function will be called **once** during the shared/root
142 * query initialization, and be expected to synchronously return the initial data. Initial data is
143 * considered stale by default unless a `staleTime` has been set. `initialData` **is persisted** to the
144 * cache. Unlike `queryKey`/`enabled`, this is not reactive β it isn't re-evaluated on `ref` changes.
145 */
146 initialData?:
147 | undefined
148 | InitialDataFunction<NonUndefinedGuard<TQueryFnData>>
149 | NonUndefinedGuard<TQueryFnData>
150}
151β
152type WithDefinedInitialData<TQueryFnData> = {
153 /**
154 * If set, this value will be used as the initial data for the query cache (as long as the query hasn't been
155 * created or cached yet). If set to a function, the function will be called **once** during the shared/root
156 * query initialization, and be expected to synchronously return the initial data. Initial data is
157 * considered stale by default unless a `staleTime` has been set. `initialData` **is persisted** to the
158 * cache. Unlike `queryKey`/`enabled`, this is not reactive β it isn't re-evaluated on `ref` changes.
159 */
160 initialData:
161 | NonUndefinedGuard<TQueryFnData>
162 | (() => NonUndefinedGuard<TQueryFnData>)
163}
164β
165/**
166 * The options accepted by the `queryOptions` overload selected when no `initialData` is set β `data` may be
167 * `undefined` while the query is `pending`.
168 * @template TQueryFnData - The type your `queryFn` resolves to.
169 * @template TError - The type of errors your `queryFn` may throw.
170 * @template TData - The type `data` ends up as after `select` runs.
171 * @template TQueryKey - The type of your `queryKey`.
172 */
173export type UndefinedInitialQueryOptions<
174 TQueryFnData = unknown,
175 TError = DefaultError,
176 TData = TQueryFnData,
177 TQueryKey extends QueryKey = QueryKey,
178> = UseQueryOptions<TQueryFnData, TError, TData, TQueryFnData, TQueryKey> &
179 WithUndefinedInitialData<TQueryFnData>
180β
181/**
182 * The options accepted by the `queryOptions` overload selected when `initialData` is set β `data` is never
183 * `undefined` (unless a `select` changes `TData` to include `undefined`).
184 * @template TQueryFnData - The type your `queryFn` resolves to.
185 * @template TError - The type of errors your `queryFn` may throw.
186 * @template TData - The type `data` ends up as after `select` runs.
187 * @template TQueryKey - The type of your `queryKey`.
188 */
189export type DefinedInitialQueryOptions<
190 TQueryFnData = unknown,
191 TError = DefaultError,
192 TData = TQueryFnData,
193 TQueryKey extends QueryKey = QueryKey,
194> = UseQueryOptions<TQueryFnData, TError, TData, TQueryFnData, TQueryKey> &
195 WithDefinedInitialData<TQueryFnData>
196β
197/**
198 * The options returned by the `queryOptions` overload selected when `initialData` is omitted or may be
199 * `undefined`, with the `queryKey` tagged with the query's data and error types.
200 */
201export type UndefinedInitialQueryOptionsWithDataTag<
202 TQueryFnData = unknown,
203 TError = DefaultError,
204 TData = TQueryFnData,
205 TQueryKey extends QueryKey = QueryKey,
206> = QueryOptions<TQueryFnData, TError, TData, TQueryFnData, TQueryKey> &
207 WithUndefinedInitialData<TQueryFnData> &
208 QueryKeyWithDataTag<TQueryKey, TQueryFnData, TError>
209β
210/**
211 * The options returned by the `queryOptions` overload selected when `initialData` is set, with the
212 * `queryKey` tagged with the query's data and error types.
213 */
214export type DefinedInitialQueryOptionsWithDataTag<
215 TQueryFnData = unknown,
216 TError = DefaultError,
217 TData = TQueryFnData,
218 TQueryKey extends QueryKey = QueryKey,
219> = QueryOptions<TQueryFnData, TError, TData, TQueryFnData, TQueryKey> &
220 WithDefinedInitialData<TQueryFnData> &
221 QueryKeyWithDataTag<TQueryKey, TQueryFnData, TError>
222β
223/**
224 * You can generally pass everything to `queryOptions` that you can also pass to `useQuery`. These options can
225 * be shared across hooks and imperative APIs such as `queryClient.query`. `options.queryKey` is required and
226 * is the query key to generate options for.
227 *
228 * This overload is selected when `initialData` is set, so the resulting `data` is never `undefined` (unless
229 * a `select` changes `TData` to include `undefined`).
230 * @param options - The {@link DefinedInitialQueryOptions} to use β everything you can pass to `useQuery`, with
231 * `initialData` set.
232 * @returns The same options object, typed so that `queryKey` carries the inferred data type.
233 * @see {@link useQuery} to run a query with these options.
234 * @example
235 * ```vue
236 * <script setup lang="ts">
237 * import { queryOptions, useQuery } from '@tanstack/vue-query'
238 *
239 * const postsOptions = queryOptions({
240 * queryKey: ['posts'],
241 * queryFn: fetchPosts,
242 * initialData: [],
243 * })
244 *
245 * // `data` is `Post[]`, never `undefined`, thanks to `initialData` β even if a refetch fails,
246 * // so the list stays visible alongside the error.
247 * const { data, isError, error } = useQuery(postsOptions)
248 * </script>
249 * ```
250 */
251export function queryOptions<
252 TQueryFnData = unknown,
253 TError = DefaultError,
254 TData = TQueryFnData,
255 TQueryKey extends QueryKey = QueryKey,
256>(
257 options: DefinedInitialQueryOptions<TQueryFnData, TError, TData, TQueryKey>,
258): DefinedInitialQueryOptionsWithDataTag<TQueryFnData, TError, TData, TQueryKey>
259β
260/**
261 * Same as the plain-object overload, but for options that close over reactive state (`ref`s read inside the
262 * function body). Wrap them in a getter so `queryClient` methods like `invalidateQueries`/`fetchQuery` always
263 * read the current values instead of the ones captured when the options were created.
264 * @param options - A function returning the {@link DefinedInitialQueryOptions} to use, re-evaluated on demand.
265 * @returns A function that returns the same options object, typed so that `queryKey` carries the inferred data
266 * type.
267 * @see {@link useQuery} to run a query with these options.
268 * @example
269 * ```vue
270 * <script setup lang="ts">
271 * import { ref } from 'vue'
272 * import { queryOptions, useQuery } from '@tanstack/vue-query'
273 *
274 * const postId = ref(1)
275 * const postOptions = queryOptions(() => ({
276 * queryKey: ['post', postId.value],
277 * queryFn: () => fetchPost(postId.value),
278 * initialData: { id: postId.value, title: '' },
279 * }))
280 *
281 * // Pass the getter itself, not `postOptions()`, so the query keeps reacting to `postId` changes.
282 * const { data } = useQuery(postOptions)
283 * </script>
284 * ```
285 */
286export function queryOptions<
287 TQueryFnData = unknown,
288 TError = DefaultError,
289 TData = TQueryFnData,
290 TQueryKey extends QueryKey = QueryKey,
291>(
292 options: () => DefinedInitialQueryOptions<
293 TQueryFnData,
294 TError,
295 TData,
296 TQueryKey
297 >,
298): () => DefinedInitialQueryOptionsWithDataTag<
299 TQueryFnData,
300 TError,
301 TData,
302 TQueryKey
303>
304β
305/**
306 * You can generally pass everything to `queryOptions` that you can also pass to `useQuery`. These options can
307 * be shared across hooks and imperative APIs such as `queryClient.query`. `options.queryKey` is required and
308 * is the query key to generate options for.
309 * @param options - The {@link UndefinedInitialQueryOptions} to use β everything you can pass to `useQuery`.
310 * @returns The same options object, typed so that `queryKey` carries the inferred data type.
311 * @see {@link useQuery} to run a query with these options.
312 * @example
313 * A parameterized factory, so the same options object can be reused per `id`:
314 * ```vue
315 * <script setup lang="ts">
316 * import { queryOptions, useQuery } from '@tanstack/vue-query'
317 *
318 * function postOptions(id: string) {
319 * return queryOptions({
320 * queryKey: ['post', id],
321 * queryFn: () => fetchPost(id),
322 * })
323 * }
324 *
325 * const { data, isPending, isError, error } = useQuery(postOptions('1'))
326 * </script>
327 * ```
328 */
329export function queryOptions<
330 TQueryFnData = unknown,
331 TError = DefaultError,
332 TData = TQueryFnData,
333 TQueryKey extends QueryKey = QueryKey,
334>(
335 options: UndefinedInitialQueryOptions<TQueryFnData, TError, TData, TQueryKey>,
336): UndefinedInitialQueryOptionsWithDataTag<
337 TQueryFnData,
338 TError,
339 TData,
340 TQueryKey
341>
342β
343/**
344 * Same as the plain-object overload, but for options that close over reactive state (`ref`s read inside the
345 * function body). Wrap them in a getter so the `queryKey` β and anything else derived from a `ref` β reacts
346 * to changes, and so `queryClient` methods like `invalidateQueries`/`fetchQuery` always read the current
347 * values instead of the ones captured when the options were created.
348 * @param options - A function returning the {@link UndefinedInitialQueryOptions} to use, re-evaluated on
349 * demand.
350 * @returns A function that returns the same options object, typed so that `queryKey` carries the inferred
351 * data type.
352 * @see {@link useQuery} to run a query with these options.
353 * @example
354 * ```vue
355 * <script setup lang="ts">
356 * import { ref } from 'vue'
357 * import { queryOptions, useQuery, useQueryClient } from '@tanstack/vue-query'
358 *
359 * const postId = ref(1)
360 * const postOptions = queryOptions(() => ({
361 * queryKey: ['post', postId.value],
362 * queryFn: () => fetchPost(postId.value),
363 * }))
364 *
365 * // Pass the getter itself, not `postOptions()`, so the query keeps reacting to `postId` changes.
366 * const { data } = useQuery(postOptions)
367 * const queryClient = useQueryClient()
368 * // Here, call `postOptions()` so `invalidateQueries` reads the current `queryKey` right away.
369 * queryClient.invalidateQueries(postOptions())
370 * </script>
371 * ```
372 * @example
373 * A parameterized factory that disables the query, type safe, until `postId` is set. The whole-options getter
374 * re-evaluates `queryFn` on every change to `postId`. `queryFn` can also be a `computed`, but never a bare
375 * getter, since a function there is the query function itself:
376 * ```vue
377 * <script setup lang="ts">
378 * import { queryOptions, skipToken, useQuery } from '@tanstack/vue-query'
379 *
380 * function postOptions(postId: number | undefined) {
381 * return queryOptions(() => ({
382 * queryKey: ['post', postId],
383 * queryFn: postId != null ? () => fetchPost(postId) : skipToken,
384 * }))
385 * }
386 *
387 * const props = defineProps<{ postId: number | undefined }>()
388 * const { data, isLoading, isError, error } = useQuery(postOptions(props.postId))
389 * </script>
390 * ```
391 */
392export function queryOptions<
393 TQueryFnData = unknown,
394 TError = DefaultError,
395 TData = TQueryFnData,
396 TQueryKey extends QueryKey = QueryKey,
397>(
398 options: () => UndefinedInitialQueryOptions<
399 TQueryFnData,
400 TError,
401 TData,
402 TQueryKey
403 >,
404): () => UndefinedInitialQueryOptionsWithDataTag<
405 TQueryFnData,
406 TError,
407 TData,
408 TQueryKey
409>
410β
411export function queryOptions(options: unknown) {
412 return options
413}