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

queryOptions.ts

415 lines15.3 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 ?
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
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>
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>)
164​
165/**
166 * The options accepted by the `queryOptions` overload selected when `initialData` is omitted, may be
167 * `undefined`, or is a function that may return `undefined` β€” `data` may be `undefined` while the query is
168 * `pending`.
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 known to be defined β€”
184 * `data` is never `undefined` (unless a `select` changes `TData` to include `undefined`).
185 * @template TQueryFnData - The type your `queryFn` resolves to.
186 * @template TError - The type of errors your `queryFn` may throw.
187 * @template TData - The type `data` ends up as after `select` runs.
188 * @template TQueryKey - The type of your `queryKey`.
189 */
190export type DefinedInitialQueryOptions<
191 TQueryFnData = unknown,
192 TError = DefaultError,
193 TData = TQueryFnData,
194 TQueryKey extends QueryKey = QueryKey,
195> = UseQueryOptions<TQueryFnData, TError, TData, TQueryFnData, TQueryKey> &
196 WithDefinedInitialData<TQueryFnData>
197​
198/**
199 * The options returned by the `queryOptions` overload selected when `initialData` is omitted, may be
200 * `undefined`, or is a function that may return `undefined`, with the `queryKey` tagged with the query's data
201 * and error types.
202 */
203export type UndefinedInitialQueryOptionsWithDataTag<
204 TQueryFnData = unknown,
205 TError = DefaultError,
206 TData = TQueryFnData,
207 TQueryKey extends QueryKey = QueryKey,
208> = QueryOptions<TQueryFnData, TError, TData, TQueryFnData, TQueryKey> &
209 WithUndefinedInitialData<TQueryFnData> &
210 QueryKeyWithDataTag<TQueryKey, TQueryFnData, TError>
211​
212/**
213 * The options returned by the `queryOptions` overload selected when `initialData` is known to be defined,
214 * with the `queryKey` tagged with the query's data and error types.
215 */
216export type DefinedInitialQueryOptionsWithDataTag<
217 TQueryFnData = unknown,
218 TError = DefaultError,
219 TData = TQueryFnData,
220 TQueryKey extends QueryKey = QueryKey,
221> = QueryOptions<TQueryFnData, TError, TData, TQueryFnData, TQueryKey> &
222 WithDefinedInitialData<TQueryFnData> &
223 QueryKeyWithDataTag<TQueryKey, TQueryFnData, TError>
224​
225/**
226 * You can generally pass everything to `queryOptions` that you can also pass to `useQuery`. These options can
227 * be shared across hooks and imperative APIs such as `queryClient.query`. `options.queryKey` is required and
228 * is the query key to generate options for.
229 *
230 * This overload is selected when `initialData` is known to be defined, so the resulting `data` is never
231 * `undefined` (unless a `select` changes `TData` to include `undefined`).
232 * @param options - The {@link DefinedInitialQueryOptions} to use β€” everything you can pass to `useQuery`,
233 * with `initialData` known to be defined.
234 * @returns The same options object, typed so that `queryKey` carries the inferred data type.
235 * @see {@link useQuery} to run a query with these options.
236 * @example
237 * ```vue
238 * <script setup lang="ts">
239 * import { queryOptions, useQuery } from '@tanstack/vue-query'
240 *
241 * const postsOptions = queryOptions({
242 * queryKey: ['posts'],
243 * queryFn: fetchPosts,
244 * initialData: [],
245 * })
246 *
247 * // `data` is `Post[]`, never `undefined`, thanks to `initialData` β€” even if a refetch fails,
248 * // so the list stays visible alongside the error.
249 * const { data, isError, error } = useQuery(postsOptions)
250 * </script>
251 * ```
252 */
253export function queryOptions<
254 TQueryFnData = unknown,
255 TError = DefaultError,
256 TData = TQueryFnData,
257 TQueryKey extends QueryKey = QueryKey,
258>(
259 options: DefinedInitialQueryOptions<TQueryFnData, TError, TData, TQueryKey>,
260): DefinedInitialQueryOptionsWithDataTag<TQueryFnData, TError, TData, TQueryKey>
261​
262/**
263 * Same as the plain-object overload, but for options that close over reactive state (`ref`s read inside the
264 * function body). Wrap them in a getter so `queryClient` methods like `invalidateQueries`/`fetchQuery` always
265 * read the current values instead of the ones captured when the options were created.
266 * @param options - A function returning the {@link DefinedInitialQueryOptions} to use, re-evaluated on demand.
267 * @returns A function that returns the same options object, typed so that `queryKey` carries the inferred data
268 * type.
269 * @see {@link useQuery} to run a query with these options.
270 * @example
271 * ```vue
272 * <script setup lang="ts">
273 * import { ref } from 'vue'
274 * import { queryOptions, useQuery } from '@tanstack/vue-query'
275 *
276 * const postId = ref(1)
277 * const postOptions = queryOptions(() => ({
278 * queryKey: ['post', postId.value],
279 * queryFn: () => fetchPost(postId.value),
280 * initialData: { id: postId.value, title: '' },
281 * }))
282 *
283 * // Pass the getter itself, not `postOptions()`, so the query keeps reacting to `postId` changes.
284 * const { data } = useQuery(postOptions)
285 * </script>
286 * ```
287 */
288export function queryOptions<
289 TQueryFnData = unknown,
290 TError = DefaultError,
291 TData = TQueryFnData,
292 TQueryKey extends QueryKey = QueryKey,
293>(
294 options: () => DefinedInitialQueryOptions<
295 TQueryFnData,
296 TError,
297 TData,
298 TQueryKey
299 >,
300): () => DefinedInitialQueryOptionsWithDataTag<
301 TQueryFnData,
302 TError,
303 TData,
304 TQueryKey
306​
307/**
308 * You can generally pass everything to `queryOptions` that you can also pass to `useQuery`. These options can
309 * be shared across hooks and imperative APIs such as `queryClient.query`. `options.queryKey` is required and
310 * is the query key to generate options for.
311 * @param options - The {@link UndefinedInitialQueryOptions} to use β€” everything you can pass to `useQuery`.
312 * @returns The same options object, typed so that `queryKey` carries the inferred data type.
313 * @see {@link useQuery} to run a query with these options.
314 * @example
315 * A parameterized factory, so the same options object can be reused per `id`:
316 * ```vue
317 * <script setup lang="ts">
318 * import { queryOptions, useQuery } from '@tanstack/vue-query'
319 *
320 * function postOptions(id: string) {
321 * return queryOptions({
322 * queryKey: ['post', id],
323 * queryFn: () => fetchPost(id),
324 * })
325 * }
326 *
327 * const { data, isPending, isError, error } = useQuery(postOptions('1'))
328 * </script>
329 * ```
330 */
331export function queryOptions<
332 TQueryFnData = unknown,
333 TError = DefaultError,
334 TData = TQueryFnData,
335 TQueryKey extends QueryKey = QueryKey,
336>(
337 options: UndefinedInitialQueryOptions<TQueryFnData, TError, TData, TQueryKey>,
338): UndefinedInitialQueryOptionsWithDataTag<
339 TQueryFnData,
340 TError,
341 TData,
342 TQueryKey
344​
345/**
346 * Same as the plain-object overload, but for options that close over reactive state (`ref`s read inside the
347 * function body). Wrap them in a getter so the `queryKey` β€” and anything else derived from a `ref` β€” reacts
348 * to changes, and so `queryClient` methods like `invalidateQueries`/`fetchQuery` always read the current
349 * values instead of the ones captured when the options were created.
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 * @see {@link useQuery} to run a query with these options.
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 * @example
375 * A parameterized factory that disables the query, type safe, until `postId` is set. The whole-options getter
376 * re-evaluates `queryFn` on every change to `postId`. `queryFn` can also be a `computed`, but never a bare
377 * getter, since a function there is the query function itself:
378 * ```vue
379 * <script setup lang="ts">
380 * import { queryOptions, skipToken, useQuery } from '@tanstack/vue-query'
381 *
382 * function postOptions(postId: number | undefined) {
383 * return queryOptions(() => ({
384 * queryKey: ['post', postId],
385 * queryFn: postId != null ? () => fetchPost(postId) : skipToken,
386 * }))
387 * }
388 *
389 * const props = defineProps<{ postId: number | undefined }>()
390 * const { data, isLoading, isError, error } = useQuery(postOptions(props.postId))
391 * </script>
392 * ```
393 */
394export function queryOptions<
395 TQueryFnData = unknown,
396 TError = DefaultError,
397 TData = TQueryFnData,
398 TQueryKey extends QueryKey = QueryKey,
399>(
400 options: () => UndefinedInitialQueryOptions<
401 TQueryFnData,
402 TError,
403 TData,
404 TQueryKey
405 >,
406): () => UndefinedInitialQueryOptionsWithDataTag<
407 TQueryFnData,
408 TError,
409 TData,
410 TQueryKey
412​
413export function queryOptions(options: unknown) {
414 return options