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

queryOptions.ts

432 lines16.2 KB

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