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 `initialData` is omitted, may be
15 * `undefined`, or is a function that may return `undefined` β `data` may be `undefined` while the query is
16 * `pending`.
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 `queryFn` is not `skipToken` and
43 * `initialData` is omitted, may be `undefined`, or is a function that may return `undefined` β same as
44 * {@link UndefinedInitialDataOptions}, but `queryFn` may not be `skipToken`.
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 `initialData` is omitted, may
61 * be `undefined`, or is a function that may return `undefined`. If you don't intend to run the query yet,
62 * set `enabled: false` β omitting `queryFn` alone still triggers a fetch that fails with "Missing queryFn"
63 * unless `enabled` is `false` or a default query function has been defined. A default query function only
64 * supplies `queryFn`; it doesn't defer the fetch on its own.
65 */
66 queryFn?: Exclude<
67 UseQueryOptions<TQueryFnData, TError, TData, TQueryKey>['queryFn'],
68 SkipToken | undefined
69 >
70}
71β
72/**
73 * The options accepted by the `queryOptions` overload selected when `initialData` is known to be defined β
74 * `data` is never `undefined` (unless a `select` changes `TData` to include `undefined`).
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 known to be defined, so the resulting `data` is never
110 * `undefined` (unless a `select` changes `TData` to include `undefined`).
111 * @param options - The {@link DefinedInitialDataOptions} to use β everything you can pass to `useQuery`, with `initialData` known to be defined.
112 * @returns The same options object, typed so that `queryKey` carries the inferred data type.
113 * @see {@link useQuery} to run a query with these options.
114 * @see [The Query Options API](https://tkdodo.eu/blog/the-query-options-api) for more on this pattern.
115 * @example
116 * ```tsx
117 * import { queryOptions, useQuery } from '@tanstack/react-query'
118 *
119 * export const postsOptions = queryOptions({
120 * queryKey: ['posts'],
121 * queryFn: fetchPosts,
122 * initialData: [],
123 * })
124 *
125 * function Posts() {
126 * // `data` is `Post[]`, never `undefined`, thanks to `initialData` β even if a refetch fails,
127 * // so the list stays visible alongside the error.
128 * const { data, isError, error } = useQuery(postsOptions)
129 *
130 * return (
131 * <div>
132 * {isError ? <span>Error: {error.message}</span> : null}
133 * <ul>
134 * {data.map((post) => <li key={post.id}>{post.title}</li>)}
135 * </ul>
136 * </div>
137 * )
138 * }
139 * ```
140 */
141export function queryOptions<
142 TQueryFnData = unknown,
143 TError = DefaultError,
144 TData = TQueryFnData,
145 TQueryKey extends QueryKey = QueryKey,
146>(
147 options: DefinedInitialDataOptions<TQueryFnData, TError, TData, TQueryKey>,
148): DefinedInitialDataOptions<TQueryFnData, TError, TData, TQueryKey> &
149 QueryKeyWithDataTag<TQueryKey, TQueryFnData, TError>
150β
151/**
152 * You can generally pass everything to `queryOptions` that you can also pass to `useQuery`. These options can
153 * be shared across hooks and imperative APIs such as `queryClient.query`. `options.queryKey` is required and
154 * is the query key to generate options for.
155 * @param options - The {@link UnusedSkipTokenOptions} to use β everything you can pass to `useQuery`.
156 * @returns The same options object, typed so that `queryKey` carries the inferred data type.
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 * @example
160 * A parameterized factory, so the same options object can be reused per `id`:
161 * ```tsx
162 * import { queryOptions, useQuery } from '@tanstack/react-query'
163 *
164 * export const postOptions = (id: string) =>
165 * queryOptions({
166 * queryKey: ['post', id],
167 * queryFn: () => fetchPost(id),
168 * })
169 *
170 * function Post({ id }: { id: string }) {
171 * const { data, isPending, isError, error } = useQuery(postOptions(id))
172 *
173 * if (isPending) return 'Loading...'
174 * if (isError) return <span>Error: {error.message}</span>
175 *
176 * return <h1>{data.title}</h1>
177 * }
178 * ```
179 */
180export function queryOptions<
181 TQueryFnData = unknown,
182 TError = DefaultError,
183 TData = TQueryFnData,
184 TQueryKey extends QueryKey = QueryKey,
185>(
186 options: UnusedSkipTokenOptions<TQueryFnData, TError, TData, TQueryKey>,
187): UnusedSkipTokenOptions<TQueryFnData, TError, TData, TQueryKey> &
188 QueryKeyWithDataTag<TQueryKey, TQueryFnData, TError>
189β
190/**
191 * You can generally pass everything to `queryOptions` that you can also pass to `useQuery`. These options can
192 * be shared across hooks and imperative APIs such as `queryClient.query`. `options.queryKey` is required and
193 * is the query key to generate options for.
194 * @param options - The {@link UndefinedInitialDataOptions} to use β everything you can pass to `useQuery`.
195 * @returns The same options object, typed so that `queryKey` carries the inferred data type.
196 * @remarks This is the only overload that accepts `queryFn: skipToken`, shown below.
197 * @see {@link useQuery} to run a query with these options.
198 * @see [The Query Options API](https://tkdodo.eu/blog/the-query-options-api) for more on this pattern.
199 * @example
200 * A parameterized factory, so the same options object can be reused per `id`:
201 * ```tsx
202 * import { queryOptions, useQuery } from '@tanstack/react-query'
203 *
204 * export const postOptions = (id: string) =>
205 * queryOptions({
206 * queryKey: ['post', id],
207 * queryFn: () => fetchPost(id),
208 * })
209 *
210 * function Post({ id }: { id: string }) {
211 * const { data, isPending, isError, error } = useQuery(postOptions(id))
212 *
213 * if (isPending) return 'Loading...'
214 * if (isError) return <span>Error: {error.message}</span>
215 *
216 * return <h1>{data.title}</h1>
217 * }
218 * ```
219 * @example
220 * A factory that disables the query, type safe, until `postId` is set:
221 * ```tsx
222 * import { queryOptions, skipToken, useQuery } from '@tanstack/react-query'
223 *
224 * export const postOptions = (postId: number | undefined) =>
225 * queryOptions({
226 * queryKey: ['post', postId],
227 * queryFn: postId != null ? () => fetchPost(postId) : skipToken,
228 * })
229 *
230 * function Post({ postId }: { postId: number | undefined }) {
231 * const { data, isLoading, isError, error } = useQuery(postOptions(postId))
232 *
233 * if (postId == null) return 'Select a post'
234 * if (isLoading) return 'Loading...'
235 * if (isError) return <span>Error: {error.message}</span>
236 *
237 * return <h1>{data?.title}</h1>
238 * }
239 * ```
240 */
241export function queryOptions<
242 TQueryFnData = unknown,
243 TError = DefaultError,
244 TData = TQueryFnData,
245 TQueryKey extends QueryKey = QueryKey,
246>(
247 options: UndefinedInitialDataOptions<TQueryFnData, TError, TData, TQueryKey>,
248): UndefinedInitialDataOptions<TQueryFnData, TError, TData, TQueryKey> &
249 QueryKeyWithDataTag<TQueryKey, TQueryFnData, TError>
250β
251export function queryOptions(options: unknown) {
252 return options
253}