Open History to see the last commit
1import type {
2 DefaultError,
3 InitialDataFunction,
4 NonUndefinedGuard,
5 OmitKeyof,
6 QueryFunction,
7 QueryKey,
8 QueryKeyWithDataTag,
9 SkipToken,
10} from '@tanstack/query-core'
11import type { UseQueryOptions } from './types'
12β
13/**
14 * The options accepted by the `queryOptions` overload selected when no
15 * `initialData` is set β `data` may be `undefined` while the query is
16 * `pending`.
17 *
18 * @template TQueryFnData - The type your `queryFn` resolves to.
19 * @template TError - The type of errors your `queryFn` may throw.
20 * @template TData - The type `data` ends up as after `select` runs.
21 * @template TQueryKey - The type of your `queryKey`.
22 */
23export type UndefinedInitialDataOptions<
24 TQueryFnData = unknown,
25 TError = DefaultError,
26 TData = TQueryFnData,
27 TQueryKey extends QueryKey = QueryKey,
28> = UseQueryOptions<TQueryFnData, TError, TData, TQueryKey> & {
29 /**
30 * If set, this value will be used as the initial data for the query cache (as
31 * long as the query hasn't been created or cached yet). If set to a function,
32 * the function will be called **once** during the shared/root query
33 * initialization, and be expected to synchronously return the initial data.
34 * Initial data is considered stale by default unless a `staleTime` has been
35 * set. `initialData` **is persisted** to the cache.
36 */
37 initialData?:
38 | undefined
39 | InitialDataFunction<NonUndefinedGuard<TQueryFnData>>
40 | NonUndefinedGuard<TQueryFnData>
41}
42β
43/**
44 * The options accepted by the `queryOptions` overload selected when no
45 * `initialData` is set and `queryFn` is not `skipToken` β same as
46 * {@link UndefinedInitialDataOptions}, but `queryFn` may not be `skipToken`.
47 *
48 * @template TQueryFnData - The type your `queryFn` resolves to.
49 * @template TError - The type of errors your `queryFn` may throw.
50 * @template TData - The type `data` ends up as after `select` runs.
51 * @template TQueryKey - The type of your `queryKey`.
52 */
53export type UnusedSkipTokenOptions<
54 TQueryFnData = unknown,
55 TError = DefaultError,
56 TData = TQueryFnData,
57 TQueryKey extends QueryKey = QueryKey,
58> = OmitKeyof<
59 UseQueryOptions<TQueryFnData, TError, TData, TQueryKey>,
60 'queryFn'
61> & {
62 /**
63 * `skipToken` is not allowed as a value here β this overload is selected when
64 * no `initialData` is set. If you don't intend to run the query yet, set
65 * `enabled: false` β omitting `queryFn` alone still triggers a fetch that
66 * fails with "Missing queryFn" unless `enabled` is `false` or a default query
67 * function has been defined. A default query function only supplies
68 * `queryFn`; it doesn't defer the fetch on its own.
69 */
70 queryFn?: Exclude<
71 UseQueryOptions<TQueryFnData, TError, TData, TQueryKey>['queryFn'],
72 SkipToken | undefined
73 >
74}
75β
76/**
77 * The options accepted by the `queryOptions` overload selected when
78 * `initialData` is set β `data` is never `undefined` (unless a `select` changes
79 * `TData` to include `undefined`).
80 *
81 * @template TQueryFnData - The type your `queryFn` resolves to.
82 * @template TError - The type of errors your `queryFn` may throw.
83 * @template TData - The type `data` ends up as after `select` runs.
84 * @template TQueryKey - The type of your `queryKey`.
85 */
86export type DefinedInitialDataOptions<
87 TQueryFnData = unknown,
88 TError = DefaultError,
89 TData = TQueryFnData,
90 TQueryKey extends QueryKey = QueryKey,
91> = Omit<UseQueryOptions<TQueryFnData, TError, TData, TQueryKey>, 'queryFn'> & {
92 /**
93 * If set, this value will be used as the initial data for the query cache (as
94 * long as the query hasn't been created or cached yet). If set to a function,
95 * the function will be called **once** during the shared/root query
96 * initialization, and be expected to synchronously return the initial data.
97 * Initial data is considered stale by default unless a `staleTime` has been
98 * set. `initialData` **is persisted** to the cache.
99 */
100 initialData:
101 | NonUndefinedGuard<TQueryFnData>
102 | (() => NonUndefinedGuard<TQueryFnData>)
103 /**
104 * Optional here, but omitting it is only safe when no fetch will be attempted
105 * β for example with `enabled: false`, or when a default query function has
106 * been defined. Otherwise, an enabled query with no `queryFn` still tries to
107 * fetch and fails with a "Missing queryFn" error; `initialData` does not
108 * prevent this.
109 */
110 queryFn?: QueryFunction<TQueryFnData, TQueryKey>
111}
112β
113/**
114 * You can generally pass everything to `queryOptions` that you can also pass to
115 * `useQuery`. These options can be shared across hooks and imperative APIs such
116 * as `queryClient.query`. `options.queryKey` is required and is the query key
117 * to generate options for.
118 *
119 * This overload is selected when `initialData` is set, so the resulting `data`
120 * is never `undefined` (unless a `select` changes `TData` to include
121 * `undefined`).
122 *
123 * @example
124 * ```tsx
125 * import { queryOptions, useQuery } from '@tanstack/react-query'
126 *
127 * export const postsOptions = queryOptions({
128 * queryKey: ['posts'],
129 * queryFn: fetchPosts,
130 * initialData: [],
131 * })
132 *
133 * function Posts() {
134 * // `data` is `Post[]`, never `undefined`, thanks to `initialData` β even if a refetch fails,
135 * // so the list stays visible alongside the error.
136 * const { data, isError, error } = useQuery(postsOptions)
137 *
138 * return (
139 * <div>
140 * {isError ? <span>Error: {error.message}</span> : null}
141 * <ul>
142 * {data.map((post) => (
143 * <li key={post.id}>{post.title}</li>
144 * ))}
145 * </ul>
146 * </div>
147 * )
148 * }
149 * ```
150 *
151 * @param options - The {@link DefinedInitialDataOptions} to use β everything
152 * you can pass to `useQuery`, with `initialData` set.
153 * @returns The same options object, typed so that `queryKey` carries the
154 * inferred data type.
155 * @see {@link useQuery} to run a query with these options.
156 * @see [The Query Options API](https://tkdodo.eu/blog/the-query-options-api) for more on this pattern.
157 */
158export function queryOptions<
159 TQueryFnData = unknown,
160 TError = DefaultError,
161 TData = TQueryFnData,
162 TQueryKey extends QueryKey = QueryKey,
163>(
164 options: DefinedInitialDataOptions<TQueryFnData, TError, TData, TQueryKey>,
165): DefinedInitialDataOptions<TQueryFnData, TError, TData, TQueryKey> &
166 QueryKeyWithDataTag<TQueryKey, TQueryFnData, TError>
167β
168/**
169 * You can generally pass everything to `queryOptions` that you can also pass to
170 * `useQuery`. These options can be shared across hooks and imperative APIs such
171 * as `queryClient.query`. `options.queryKey` is required and is the query key
172 * to generate options for.
173 *
174 * @example
175 * A parameterized factory, so the same options object can be reused per `id`:
176 * ```tsx
177 * import { queryOptions, useQuery } from '@tanstack/react-query'
178 *
179 * export const postOptions = (id: string) =>
180 * queryOptions({
181 * queryKey: ['post', id],
182 * queryFn: () => fetchPost(id),
183 * })
184 *
185 * function Post({ id }: { id: string }) {
186 * const { data, isPending, isError, error } = useQuery(postOptions(id))
187 *
188 * if (isPending) return 'Loading...'
189 * if (isError) return <span>Error: {error.message}</span>
190 *
191 * return <h1>{data.title}</h1>
192 * }
193 * ```
194 *
195 * @param options - The {@link UnusedSkipTokenOptions} to use β everything you
196 * can pass to `useQuery`.
197 * @returns The same options object, typed so that `queryKey` carries the
198 * inferred data type.
199 * @see {@link useQuery} to run a query with these options.
200 * @see [The Query Options API](https://tkdodo.eu/blog/the-query-options-api) for more on this pattern.
201 */
202export function queryOptions<
203 TQueryFnData = unknown,
204 TError = DefaultError,
205 TData = TQueryFnData,
206 TQueryKey extends QueryKey = QueryKey,
207>(
208 options: UnusedSkipTokenOptions<TQueryFnData, TError, TData, TQueryKey>,
209): UnusedSkipTokenOptions<TQueryFnData, TError, TData, TQueryKey> &
210 QueryKeyWithDataTag<TQueryKey, TQueryFnData, TError>
211β
212/**
213 * You can generally pass everything to `queryOptions` that you can also pass to
214 * `useQuery`. These options can be shared across hooks and imperative APIs such
215 * as `queryClient.query`. `options.queryKey` is required and is the query key
216 * to generate options for.
217 *
218 * @remarks
219 * This is the only overload that accepts `queryFn: skipToken`, shown below.
220 * @example
221 * A parameterized factory, so the same options object can be reused per `id`:
222 * ```tsx
223 * import { queryOptions, useQuery } from '@tanstack/react-query'
224 *
225 * export const postOptions = (id: string) =>
226 * queryOptions({
227 * queryKey: ['post', id],
228 * queryFn: () => fetchPost(id),
229 * })
230 *
231 * function Post({ id }: { id: string }) {
232 * const { data, isPending, isError, error } = useQuery(postOptions(id))
233 *
234 * if (isPending) return 'Loading...'
235 * if (isError) return <span>Error: {error.message}</span>
236 *
237 * return <h1>{data.title}</h1>
238 * }
239 * ```
240 *
241 * @example
242 * A factory that disables the query, type safe, until `postId` is set:
243 * ```tsx
244 * import { queryOptions, skipToken, useQuery } from '@tanstack/react-query'
245 *
246 * export const postOptions = (postId: number | undefined) =>
247 * queryOptions({
248 * queryKey: ['post', postId],
249 * queryFn: postId != null ? () => fetchPost(postId) : skipToken,
250 * })
251 *
252 * function Post({ postId }: { postId: number | undefined }) {
253 * const { data, isLoading, isError, error } = useQuery(postOptions(postId))
254 *
255 * if (postId == null) return 'Select a post'
256 * if (isLoading) return 'Loading...'
257 * if (isError) return <span>Error: {error.message}</span>
258 *
259 * return <h1>{data?.title}</h1>
260 * }
261 * ```
262 *
263 * @param options - The {@link UndefinedInitialDataOptions} to use β everything
264 * you can pass to `useQuery`.
265 * @returns The same options object, typed so that `queryKey` carries the
266 * inferred data type.
267 * @see {@link useQuery} to run a query with these options.
268 * @see [The Query Options API](https://tkdodo.eu/blog/the-query-options-api) for more on this pattern.
269 */
270export function queryOptions<
271 TQueryFnData = unknown,
272 TError = DefaultError,
273 TData = TQueryFnData,
274 TQueryKey extends QueryKey = QueryKey,
275>(
276 options: UndefinedInitialDataOptions<TQueryFnData, TError, TData, TQueryKey>,
277): UndefinedInitialDataOptions<TQueryFnData, TError, TData, TQueryKey> &
278 QueryKeyWithDataTag<TQueryKey, TQueryFnData, TError>
279β
280export function queryOptions(options: unknown) {
281 return options
282}