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

queryOptions.ts

454 lines15.4 KB

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