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