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

queryOptions.ts

416 lines14.8 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 *
23 * @template TQueryFnData - The type your `queryFn` resolves to.
24 * @template TError - The type of errors your `queryFn` may throw.
25 * @template TData - The type `data` ends up as after `select` runs.
26 * @template TQueryData - The type of data stored in the cache, before `select` runs. Defaults to
27 * `TQueryFnData` and can be configured independently of it.
28 * @template TQueryKey - The type of your `queryKey`.
29 */
30export type QueryOptions<
31 TQueryFnData = unknown,
32 TError = DefaultError,
33 TData = TQueryFnData,
34 TQueryData = TQueryFnData,
35 TQueryKey extends QueryKey = QueryKey,
36> = {
37 [
38 Property in keyof QueryObserverOptions<
39 TQueryFnData,
40 TError,
41 TData,
42 TQueryData,
43 TQueryKey
44 >
45 ]: Property extends 'enabled'
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 *
85 * @template TQueryFnData - The type your `queryFn` resolves to.
86 * @template TError - The type of errors your `queryFn` may throw.
87 * @template TData - The type `data` ends up as after `select` runs.
88 * @template TQueryData - The type of data stored in the cache, before `select` runs. Defaults to
89 * `TQueryFnData` and can be configured independently of it.
90 * @template TQueryKey - The type of your `queryKey`.
91 */
92export type UseQueryOptions<
93 TQueryFnData = unknown,
94 TError = DefaultError,
95 TData = TQueryFnData,
96 TQueryData = TQueryFnData,
97 TQueryKey extends QueryKey = QueryKey,
98> = MaybeRef<
99 {
100 [
101 Property in keyof QueryObserverOptions<
102 TQueryFnData,
103 TError,
104 TData,
105 TQueryData,
106 TQueryKey
107 >
108 ]: Property extends 'enabled' | 'queryKey'
109 ? QueryOptions<
110 TQueryFnData,
111 TError,
112 TData,
113 TQueryData,
114 TQueryKey
115 >[Property]
116 : Property extends 'queryFn'
117 ? MaybeRefDeep<
118 | QueryOptions<
119 TQueryFnData,
120 TError,
121 TData,
122 TQueryData,
123 TQueryKey
124 >[Property]
125 | SkipTokenForUseQuery
126 >
127 : MaybeRefDeep<
128 QueryOptions<
129 TQueryFnData,
130 TError,
131 TData,
132 TQueryData,
133 TQueryKey
134 >[Property]
135 >
136 } & ShallowOption
138​
139type WithUndefinedInitialData<TQueryFnData> = {
140 /**
141 * If set, this value will be used as the initial data for the query cache (as long as the query hasn't been
142 * created or cached yet). If set to a function, the function will be called **once** during the shared/root
143 * query initialization, and be expected to synchronously return the initial data. Initial data is
144 * considered stale by default unless a `staleTime` has been set. `initialData` **is persisted** to the
145 * cache. Unlike `queryKey`/`enabled`, this is not reactive β€” it isn't re-evaluated on `ref` changes.
146 */
147 initialData?:
148 | undefined
149 | InitialDataFunction<NonUndefinedGuard<TQueryFnData>>
150 | NonUndefinedGuard<TQueryFnData>
152​
153type WithDefinedInitialData<TQueryFnData> = {
154 /**
155 * If set, this value will be used as the initial data for the query cache (as long as the query hasn't been
156 * created or cached yet). If set to a function, the function will be called **once** during the shared/root
157 * query initialization, and be expected to synchronously return the initial data. Initial data is
158 * considered stale by default unless a `staleTime` has been set. `initialData` **is persisted** to the
159 * cache. Unlike `queryKey`/`enabled`, this is not reactive β€” it isn't re-evaluated on `ref` changes.
160 */
161 initialData:
162 NonUndefinedGuard<TQueryFnData> | (() => NonUndefinedGuard<TQueryFnData>)
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 *
169 * @template TQueryFnData - The type your `queryFn` resolves to.
170 * @template TError - The type of errors your `queryFn` may throw.
171 * @template TData - The type `data` ends up as after `select` runs.
172 * @template TQueryKey - The type of your `queryKey`.
173 */
174export type UndefinedInitialQueryOptions<
175 TQueryFnData = unknown,
176 TError = DefaultError,
177 TData = TQueryFnData,
178 TQueryKey extends QueryKey = QueryKey,
179> = UseQueryOptions<TQueryFnData, TError, TData, TQueryFnData, TQueryKey> &
180 WithUndefinedInitialData<TQueryFnData>
181​
182/**
183 * The options accepted by the `queryOptions` overload selected when `initialData` is set β€” `data` is never
184 * `undefined` (unless a `select` changes `TData` to include `undefined`).
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 DefinedInitialQueryOptions<
192 TQueryFnData = unknown,
193 TError = DefaultError,
194 TData = TQueryFnData,
195 TQueryKey extends QueryKey = QueryKey,
196> = UseQueryOptions<TQueryFnData, TError, TData, TQueryFnData, TQueryKey> &
197 WithDefinedInitialData<TQueryFnData>
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​
208export type DefinedInitialQueryOptionsWithDataTag<
209 TQueryFnData = unknown,
210 TError = DefaultError,
211 TData = TQueryFnData,
212 TQueryKey extends QueryKey = QueryKey,
213> = QueryOptions<TQueryFnData, TError, TData, TQueryFnData, TQueryKey> &
214 WithDefinedInitialData<TQueryFnData> &
215 QueryKeyWithDataTag<TQueryKey, TQueryFnData, TError>
216​
217/**
218 * You can generally pass everything to `queryOptions` that you can also pass to `useQuery`. These options can
219 * be shared across hooks and imperative APIs such as `queryClient.query`. `options.queryKey` is required and
220 * is the query key to generate options for.
221 *
222 * This overload is selected when `initialData` is set, so the resulting `data` is never `undefined` (unless
223 * a `select` changes `TData` to include `undefined`).
224 *
225 * @see {@link useQuery} to run a query with these options.
226 * @param options - The {@link DefinedInitialQueryOptions} to use β€” everything you can pass to `useQuery`, with
227 * `initialData` set.
228 * @returns The same options object, typed so that `queryKey` carries the inferred data type.
229 *
230 * @example
231 * ```vue
232 * <script setup lang="ts">
233 * import { queryOptions, useQuery } from '@tanstack/vue-query'
234 *
235 * const postsOptions = queryOptions({
236 * queryKey: ['posts'],
237 * queryFn: fetchPosts,
238 * initialData: [],
239 * })
240 *
241 * // `data` is `Post[]`, never `undefined`, thanks to `initialData` β€” even if a refetch fails,
242 * // so the list stays visible alongside the error.
243 * const { data, isError, error } = useQuery(postsOptions)
244 * </script>
245 * ```
246 */
247export function queryOptions<
248 TQueryFnData = unknown,
249 TError = DefaultError,
250 TData = TQueryFnData,
251 TQueryKey extends QueryKey = QueryKey,
252>(
253 options: DefinedInitialQueryOptions<TQueryFnData, TError, TData, TQueryKey>,
254): DefinedInitialQueryOptionsWithDataTag<TQueryFnData, TError, TData, TQueryKey>
255​
256/**
257 * Same as the plain-object overload, but for options that close over reactive state (`ref`s read inside the
258 * function body). Wrap them in a getter so `queryClient` methods like `invalidateQueries`/`fetchQuery` always
259 * read the current values instead of the ones captured when the options were created.
260 *
261 * @see {@link useQuery} to run a query with these options.
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 *
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 *
308 * @see {@link useQuery} to run a query with these options.
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 *
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
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 *
349 * @see {@link useQuery} to run a query with these options.
350 * @param options - A function returning the {@link UndefinedInitialQueryOptions} to use, re-evaluated on
351 * demand.
352 * @returns A function that returns the same options object, typed so that `queryKey` carries the inferred
353 * data type.
354 *
355 * @example
356 * ```vue
357 * <script setup lang="ts">
358 * import { ref } from 'vue'
359 * import { queryOptions, useQuery, useQueryClient } from '@tanstack/vue-query'
360 *
361 * const postId = ref(1)
362 * const postOptions = queryOptions(() => ({
363 * queryKey: ['post', postId.value],
364 * queryFn: () => fetchPost(postId.value),
365 * }))
366 *
367 * // Pass the getter itself, not `postOptions()`, so the query keeps reacting to `postId` changes.
368 * const { data } = useQuery(postOptions)
369 * const queryClient = useQueryClient()
370 * // Here, call `postOptions()` so `invalidateQueries` reads the current `queryKey` right away.
371 * queryClient.invalidateQueries(postOptions())
372 * </script>
373 * ```
374 *
375 * @example
376 * A parameterized factory that disables the query, type safe, until `postId` is set. The whole-options getter
377 * re-evaluates `queryFn` on every change to `postId`. `queryFn` can also be a `computed`, but never a bare
378 * getter, since a function there is the query function itself:
379 * ```vue
380 * <script setup lang="ts">
381 * import { queryOptions, skipToken, useQuery } from '@tanstack/vue-query'
382 *
383 * function postOptions(postId: number | undefined) {
384 * return queryOptions(() => ({
385 * queryKey: ['post', postId],
386 * queryFn: postId != null ? () => fetchPost(postId) : skipToken,
387 * }))
388 * }
389 *
390 * const props = defineProps<{ postId: number | undefined }>()
391 * const { data, isLoading, isError, error } = useQuery(postOptions(props.postId))
392 * </script>
393 * ```
394 */
395export function queryOptions<
396 TQueryFnData = unknown,
397 TError = DefaultError,
398 TData = TQueryFnData,
399 TQueryKey extends QueryKey = QueryKey,
400>(
401 options: () => UndefinedInitialQueryOptions<
402 TQueryFnData,
403 TError,
404 TData,
405 TQueryKey
406 >,
407): () => UndefinedInitialQueryOptionsWithDataTag<
408 TQueryFnData,
409 TError,
410 TData,
411 TQueryKey
413​
414export function queryOptions(options: unknown) {
415 return options