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

queryOptions.ts

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