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

queryOptions.ts

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