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

queryOptions.ts

337 lines12.4 KB

1import type { DeepUnwrapRef, MaybeRefOrGetter, ShallowOption } from './types'
2import type {
3 DefaultError,
4 InitialDataFunction,
5 NonUndefinedGuard,
6 QueryBooleanOption,
7 QueryKey,
8 QueryKeyWithDataTag,
9 QueryObserverOptions,
10} from '@tanstack/query-core'
11​
12/**
13 * The options accepted by `queryOptions`, `useQuery`, and the other query hooks. `enabled` tracks reactive
14 * dependencies automatically as a `ref`, a plain value, or a reactive getter (`() => ...`). `queryKey` reacts
15 * through a `ref` for the array itself, or `ref`s and reactive getters as individual entries β€” the array
16 * itself can't be a bare getter. Other options passed this way are read once and are not reactive.
17 *
18 * If you instead pass a getter for the whole options object (`useQuery(() => ({ ... }))`), every option
19 * inside it β€” including `staleTime`, `retry`, and `select` β€” is re-evaluated whenever the getter's own
20 * reactive dependencies change, since the entire object is recomputed.
21 *
22 * `select` only re-runs when `data` changes, or when the `select` function's own reference changes. Since a
23 * Vue `setup()` function runs only once per component instance, an inline `select` function passed directly
24 * to `queryOptions`/`useQuery` already has a stable reference across reactive updates. An inline `select`
25 * created inside a whole-options getter is recreated β€” and so can change reference β€” every time that getter
26 * re-evaluates.
27 *
28 * @template TQueryFnData - The type your `queryFn` resolves to.
29 * @template TError - The type of errors your `queryFn` may throw.
30 * @template TData - The type `data` ends up as after `select` runs.
31 * @template TQueryData - The type of data stored in the cache, before `select` runs. Defaults to
32 * `TQueryFnData` and can be configured independently of it.
33 * @template TQueryKey - The type of your `queryKey`.
34 */
35export type QueryOptions<
36 TQueryFnData = unknown,
37 TError = DefaultError,
38 TData = TQueryFnData,
39 TQueryData = TQueryFnData,
40 TQueryKey extends QueryKey = QueryKey,
41> = {
42 [Property in keyof QueryObserverOptions<
43 TQueryFnData,
44 TError,
45 TData,
46 TQueryData,
47 TQueryKey
48 >]: Property extends 'enabled'
49 ?
50 | MaybeRefOrGetter<boolean | undefined>
51 | (() => QueryBooleanOption<
52 TQueryFnData,
53 TError,
54 TQueryData,
55 DeepUnwrapRef<TQueryKey>
56 >)
57 : Property extends 'queryKey'
58 ? MaybeRefOrGetter<TQueryKey>
59 : QueryObserverOptions<
60 TQueryFnData,
61 TError,
62 TData,
63 TQueryData,
64 DeepUnwrapRef<TQueryKey>
65 >[Property]
66} & ShallowOption
67​
68/**
69 * The options accepted by the `queryOptions` overload selected when no `initialData` is set β€” `data` may be
70 * `undefined` while the query is `pending`.
71 *
72 * @template TQueryFnData - The type your `queryFn` resolves to.
73 * @template TError - The type of errors your `queryFn` may throw.
74 * @template TData - The type `data` ends up as after `select` runs.
75 * @template TQueryKey - The type of your `queryKey`.
76 */
77export type UndefinedInitialQueryOptions<
78 TQueryFnData = unknown,
79 TError = DefaultError,
80 TData = TQueryFnData,
81 TQueryKey extends QueryKey = QueryKey,
82> = QueryOptions<TQueryFnData, TError, TData, TQueryFnData, TQueryKey> & {
83 /**
84 * If set, this value will be used as the initial data for the query cache (as long as the query hasn't been
85 * created or cached yet). If set to a function, the function will be called **once** during the shared/root
86 * query initialization, and be expected to synchronously return the initial data. Initial data is
87 * considered stale by default unless a `staleTime` has been set. `initialData` **is persisted** to the
88 * cache. Unlike `queryKey`/`enabled`, this is not reactive β€” it isn't re-evaluated on `ref` changes.
89 */
90 initialData?:
91 | undefined
92 | InitialDataFunction<NonUndefinedGuard<TQueryFnData>>
93 | NonUndefinedGuard<TQueryFnData>
95​
96/**
97 * The options accepted by the `queryOptions` overload selected when `initialData` is set β€” `data` is never
98 * `undefined`.
99 *
100 * @template TQueryFnData - The type your `queryFn` resolves to.
101 * @template TError - The type of errors your `queryFn` may throw.
102 * @template TData - The type `data` ends up as after `select` runs.
103 * @template TQueryKey - The type of your `queryKey`.
104 */
105export type DefinedInitialQueryOptions<
106 TQueryFnData = unknown,
107 TError = DefaultError,
108 TData = TQueryFnData,
109 TQueryKey extends QueryKey = QueryKey,
110> = QueryOptions<TQueryFnData, TError, TData, TQueryFnData, TQueryKey> & {
111 /**
112 * If set, this value will be used as the initial data for the query cache (as long as the query hasn't been
113 * created or cached yet). If set to a function, the function will be called **once** during the shared/root
114 * query initialization, and be expected to synchronously return the initial data. Initial data is
115 * considered stale by default unless a `staleTime` has been set. `initialData` **is persisted** to the
116 * cache. Unlike `queryKey`/`enabled`, this is not reactive β€” it isn't re-evaluated on `ref` changes.
117 */
118 initialData:
119 | NonUndefinedGuard<TQueryFnData>
120 | (() => NonUndefinedGuard<TQueryFnData>)
122​
123export type UndefinedInitialQueryOptionsWithDataTag<
124 TQueryFnData = unknown,
125 TError = DefaultError,
126 TData = TQueryFnData,
127 TQueryKey extends QueryKey = QueryKey,
128> = UndefinedInitialQueryOptions<TQueryFnData, TError, TData, TQueryKey> &
129 QueryKeyWithDataTag<TQueryKey, TQueryFnData, TError>
130​
131export type DefinedInitialQueryOptionsWithDataTag<
132 TQueryFnData = unknown,
133 TError = DefaultError,
134 TData = TQueryFnData,
135 TQueryKey extends QueryKey = QueryKey,
136> = DefinedInitialQueryOptions<TQueryFnData, TError, TData, TQueryKey> &
137 QueryKeyWithDataTag<TQueryKey, TQueryFnData, TError>
138​
139/**
140 * You can generally pass everything to `queryOptions` that you can also pass to `useQuery`. These options can
141 * be shared across hooks and imperative APIs such as `queryClient.query`. `options.queryKey` is required and
142 * is the query key to generate options for.
143 *
144 * This overload is selected when `initialData` is set, so the resulting `data` is never `undefined`.
145 *
146 * @see {@link useQuery} to run a query with these options.
147 * @param options - The {@link DefinedInitialQueryOptions} to use β€” everything you can pass to `useQuery`, with
148 * `initialData` set.
149 * @returns The same options object, typed so that `queryKey` carries the inferred data type.
150 *
151 * @example
152 * ```vue
153 * <script setup lang="ts">
154 * import { queryOptions, useQuery } from '@tanstack/vue-query'
155 *
156 * const postsOptions = queryOptions({
157 * queryKey: ['posts'],
158 * queryFn: fetchPosts,
159 * initialData: [],
160 * })
161 *
162 * // `data` is `Post[]`, never `undefined`, thanks to `initialData` β€” even if a refetch fails,
163 * // so the list stays visible alongside the error.
164 * const { data, isError, error } = useQuery(postsOptions)
165 * </script>
166 * ```
167 */
168export function queryOptions<
169 TQueryFnData = unknown,
170 TError = DefaultError,
171 TData = TQueryFnData,
172 TQueryKey extends QueryKey = QueryKey,
173>(
174 options: DefinedInitialQueryOptions<TQueryFnData, TError, TData, TQueryKey>,
175): DefinedInitialQueryOptionsWithDataTag<TQueryFnData, TError, TData, TQueryKey>
176​
177/**
178 * Same as the plain-object overload, but for options that close over reactive state (`ref`s read inside the
179 * function body). Wrap them in a getter so `queryClient` methods like `invalidateQueries`/`fetchQuery` always
180 * read the current values instead of the ones captured when the options were created.
181 *
182 * @see {@link useQuery} to run a query with these options.
183 * @param options - A function returning the {@link DefinedInitialQueryOptions} to use, re-evaluated on demand.
184 * @returns A function that returns the same options object, typed so that `queryKey` carries the inferred data
185 * type.
186 *
187 * @example
188 * ```vue
189 * <script setup lang="ts">
190 * import { ref } from 'vue'
191 * import { queryOptions, useQuery } from '@tanstack/vue-query'
192 *
193 * const postId = ref(1)
194 * const postOptions = queryOptions(() => ({
195 * queryKey: ['post', postId.value],
196 * queryFn: () => fetchPost(postId.value),
197 * initialData: { id: postId.value, title: '' },
198 * }))
199 *
200 * // Pass the getter itself, not `postOptions()`, so the query keeps reacting to `postId` changes.
201 * const { data } = useQuery(postOptions)
202 * </script>
203 * ```
204 */
205export function queryOptions<
206 TQueryFnData = unknown,
207 TError = DefaultError,
208 TData = TQueryFnData,
209 TQueryKey extends QueryKey = QueryKey,
210>(
211 options: () => DefinedInitialQueryOptions<
212 TQueryFnData,
213 TError,
214 TData,
215 TQueryKey
216 >,
217): () => DefinedInitialQueryOptionsWithDataTag<
218 TQueryFnData,
219 TError,
220 TData,
221 TQueryKey
223​
224/**
225 * You can generally pass everything to `queryOptions` that you can also pass to `useQuery`. These options can
226 * be shared across hooks and imperative APIs such as `queryClient.query`. `options.queryKey` is required and
227 * is the query key to generate options for.
228 *
229 * @see {@link useQuery} to run a query with these options.
230 * @param options - The {@link UndefinedInitialQueryOptions} to use β€” everything you can pass to `useQuery`.
231 * @returns The same options object, typed so that `queryKey` carries the inferred data type.
232 *
233 * @example
234 * A parameterized factory, so the same options object can be reused per `id`:
235 * ```vue
236 * <script setup lang="ts">
237 * import { queryOptions, useQuery } from '@tanstack/vue-query'
238 *
239 * function postOptions(id: string) {
240 * return queryOptions({
241 * queryKey: ['post', id],
242 * queryFn: () => fetchPost(id),
243 * })
244 * }
245 *
246 * const { data, isPending, isError, error } = useQuery(postOptions('1'))
247 * </script>
248 * ```
249 */
250export function queryOptions<
251 TQueryFnData = unknown,
252 TError = DefaultError,
253 TData = TQueryFnData,
254 TQueryKey extends QueryKey = QueryKey,
255>(
256 options: UndefinedInitialQueryOptions<TQueryFnData, TError, TData, TQueryKey>,
257): UndefinedInitialQueryOptionsWithDataTag<
258 TQueryFnData,
259 TError,
260 TData,
261 TQueryKey
263​
264/**
265 * Same as the plain-object overload, but for options that close over reactive state (`ref`s read inside the
266 * function body). Wrap them in a getter so the `queryKey` β€” and anything else derived from a `ref` β€” reacts
267 * to changes, and so `queryClient` methods like `invalidateQueries`/`fetchQuery` always read the current
268 * values instead of the ones captured when the options were created.
269 *
270 * @see {@link useQuery} to run a query with these options.
271 * @param options - A function returning the {@link UndefinedInitialQueryOptions} to use, re-evaluated on
272 * demand.
273 * @returns A function that returns the same options object, typed so that `queryKey` carries the inferred
274 * data type.
275 *
276 * @example
277 * ```vue
278 * <script setup lang="ts">
279 * import { ref } from 'vue'
280 * import { queryOptions, useQuery, useQueryClient } from '@tanstack/vue-query'
281 *
282 * const postId = ref(1)
283 * const postOptions = queryOptions(() => ({
284 * queryKey: ['post', postId.value],
285 * queryFn: () => fetchPost(postId.value),
286 * }))
287 *
288 * // Pass the getter itself, not `postOptions()`, so the query keeps reacting to `postId` changes.
289 * const { data } = useQuery(postOptions)
290 * const queryClient = useQueryClient()
291 * // Here, call `postOptions()` so `invalidateQueries` reads the current `queryKey` right away.
292 * queryClient.invalidateQueries(postOptions())
293 * </script>
294 * ```
295 *
296 * @example
297 * A parameterized factory that disables the query, type safe, until `postId` is set. This requires a
298 * whole-options getter: `queryFn` is a single value, not `queryKey`/`enabled`, so it isn't itself reactive β€”
299 * the getter is what re-evaluates it on every change to `postId`:
300 * ```vue
301 * <script setup lang="ts">
302 * import { queryOptions, skipToken, useQuery } from '@tanstack/vue-query'
303 *
304 * function postOptions(postId: number | undefined) {
305 * return queryOptions(() => ({
306 * queryKey: ['post', postId],
307 * queryFn: postId != null ? () => fetchPost(postId) : skipToken,
308 * }))
309 * }
310 *
311 * const props = defineProps<{ postId: number | undefined }>()
312 * const { data, isLoading, isError, error } = useQuery(postOptions(props.postId))
313 * </script>
314 * ```
315 */
316export function queryOptions<
317 TQueryFnData = unknown,
318 TError = DefaultError,
319 TData = TQueryFnData,
320 TQueryKey extends QueryKey = QueryKey,
321>(
322 options: () => UndefinedInitialQueryOptions<
323 TQueryFnData,
324 TError,
325 TData,
326 TQueryKey
327 >,
328): () => UndefinedInitialQueryOptionsWithDataTag<
329 TQueryFnData,
330 TError,
331 TData,
332 TQueryKey
334​
335export function queryOptions(options: unknown) {
336 return options