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'
11β
12import type { UseQueryOptions } from './types'
13β
14/**
15 * The options accepted by the `queryOptions` overload selected when no `initialData` is set β `data` may be
16 * `undefined` while the query is `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 long as the query hasn't been
31 * created or cached yet). If set to a function, the function will be called **once** during the shared/root
32 * query initialization, and be expected to synchronously return the initial data. Initial data is
33 * considered stale by default unless a `staleTime` has been set. `initialData` **is persisted** to the
34 * cache.
35 */
36 initialData?:
37 | undefined
38 | InitialDataFunction<NonUndefinedGuard<TQueryFnData>>
39 | NonUndefinedGuard<TQueryFnData>
40}
41β
42/**
43 * The options accepted by the `queryOptions` overload selected when no `initialData` is set and `queryFn` is
44 * not `skipToken` β same as {@link UndefinedInitialDataOptions}, but `queryFn` may not be `skipToken`.
45 *
46 * @template TQueryFnData - The type your `queryFn` resolves to.
47 * @template TError - The type of errors your `queryFn` may throw.
48 * @template TData - The type `data` ends up as after `select` runs.
49 * @template TQueryKey - The type of your `queryKey`.
50 */
51export type UnusedSkipTokenOptions<
52 TQueryFnData = unknown,
53 TError = DefaultError,
54 TData = TQueryFnData,
55 TQueryKey extends QueryKey = QueryKey,
56> = OmitKeyof<
57 UseQueryOptions<TQueryFnData, TError, TData, TQueryKey>,
58 'queryFn'
59> & {
60 /**
61 * `skipToken` is not allowed as a value here β this overload is selected when no `initialData` is set. If
62 * you don't intend to run the query yet, omit `queryFn` or use a default query function instead.
63 */
64 queryFn?: Exclude<
65 UseQueryOptions<TQueryFnData, TError, TData, TQueryKey>['queryFn'],
66 SkipToken | undefined
67 >
68}
69β
70/**
71 * The options accepted by the `queryOptions` overload selected when `initialData` is set β `data` is never
72 * `undefined`.
73 *
74 * @template TQueryFnData - The type your `queryFn` resolves to.
75 * @template TError - The type of errors your `queryFn` may throw.
76 * @template TData - The type `data` ends up as after `select` runs.
77 * @template TQueryKey - The type of your `queryKey`.
78 */
79export type DefinedInitialDataOptions<
80 TQueryFnData = unknown,
81 TError = DefaultError,
82 TData = TQueryFnData,
83 TQueryKey extends QueryKey = QueryKey,
84> = Omit<UseQueryOptions<TQueryFnData, TError, TData, TQueryKey>, 'queryFn'> & {
85 /**
86 * If set, this value will be used as the initial data for the query cache (as long as the query hasn't been
87 * created or cached yet). If set to a function, the function will be called **once** during the shared/root
88 * query initialization, and be expected to synchronously return the initial data. Initial data is
89 * considered stale by default unless a `staleTime` has been set. `initialData` **is persisted** to the
90 * cache.
91 */
92 initialData:
93 | NonUndefinedGuard<TQueryFnData>
94 | (() => NonUndefinedGuard<TQueryFnData>)
95 /**
96 * Optional here, but omitting it is only safe when no fetch will be attempted β for example with
97 * `enabled: false`, or when a default query function has been defined. Otherwise, an enabled query with no
98 * `queryFn` still tries to fetch and fails with a "Missing queryFn" error; `initialData` does not prevent this.
99 */
100 queryFn?: QueryFunction<TQueryFnData, TQueryKey>
101}
102β
103/**
104 * You can generally pass everything to `queryOptions` that you can also pass to `useQuery`. These options can
105 * be shared across hooks and imperative APIs such as `queryClient.query`. `options.queryKey` is required and
106 * is the query key to generate options for.
107 *
108 * This overload is selected when `initialData` is set, so the resulting `data` is never `undefined`.
109 *
110 * @see {@link useQuery} to run a query with these options.
111 * @param options - The {@link DefinedInitialDataOptions} to use β everything you can pass to `useQuery`, with `initialData` set.
112 * @returns The same options object, typed so that `queryKey` carries the inferred data type.
113 *
114 * @example
115 * ```tsx
116 * import { queryOptions, useQuery } from '@tanstack/preact-query'
117 *
118 * export const postsOptions = queryOptions({
119 * queryKey: ['posts'],
120 * queryFn: fetchPosts,
121 * initialData: [],
122 * })
123 *
124 * function Posts() {
125 * // `data` is `Post[]`, never `undefined`, thanks to `initialData` β even if a refetch fails,
126 * // so the list stays visible alongside the error.
127 * const { data, isError, error } = useQuery(postsOptions)
128 *
129 * return (
130 * <div>
131 * {isError ? <span>Error: {error.message}</span> : null}
132 * <ul>
133 * {data.map((post) => <li key={post.id}>{post.title}</li>)}
134 * </ul>
135 * </div>
136 * )
137 * }
138 * ```
139 */
140export function queryOptions<
141 TQueryFnData = unknown,
142 TError = DefaultError,
143 TData = TQueryFnData,
144 TQueryKey extends QueryKey = QueryKey,
145>(
146 options: DefinedInitialDataOptions<TQueryFnData, TError, TData, TQueryKey>,
147): DefinedInitialDataOptions<TQueryFnData, TError, TData, TQueryKey> &
148 QueryKeyWithDataTag<TQueryKey, TQueryFnData, TError>
149β
150/**
151 * You can generally pass everything to `queryOptions` that you can also pass to `useQuery`. These options can
152 * be shared across hooks and imperative APIs such as `queryClient.query`. `options.queryKey` is required and
153 * is the query key to generate options for.
154 *
155 * @see {@link useQuery} to run a query with these options.
156 * @param options - The {@link UnusedSkipTokenOptions} to use β everything you can pass to `useQuery`.
157 * @returns The same options object, typed so that `queryKey` carries the inferred data type.
158 *
159 * @example
160 * A parameterized factory, reused across a hook and an imperative call with the same cache entry:
161 * ```tsx
162 * import { noop, queryOptions, useQuery } from '@tanstack/preact-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 * // `postOptions` also works with imperative APIs like `queryClient.query` β
180 * // see `useQuery` for an example that warms the cache this way before rendering `<Post>`.
181 * const postId = '1'
182 * queryClient.query(postOptions(postId)).catch(noop)
183 * ```
184 *
185 * @example
186 * The same options object works with every API that accepts query options:
187 * ```tsx
188 * import { noop, queryOptions, useQuery } from '@tanstack/preact-query'
189 *
190 * const todosOptions = queryOptions({
191 * queryKey: ['todos'],
192 * queryFn: fetchTodos,
193 * })
194 *
195 * function Todos() {
196 * const { data, isPending, isError, error } = useQuery(todosOptions)
197 *
198 * if (isPending) return 'Loading...'
199 * if (isError) return <span>Error: {error.message}</span>
200 *
201 * return (
202 * <ul>
203 * {data.map((todo) => <li key={todo.id}>{todo.title}</li>)}
204 * </ul>
205 * )
206 * }
207 *
208 * // The same options object works with the imperative APIs too:
209 * queryClient.query(todosOptions).catch(noop)
210 * queryClient.getQueryData(todosOptions.queryKey) // typed as Array<Todo> | undefined
211 * ```
212 */
213export function queryOptions<
214 TQueryFnData = unknown,
215 TError = DefaultError,
216 TData = TQueryFnData,
217 TQueryKey extends QueryKey = QueryKey,
218>(
219 options: UnusedSkipTokenOptions<TQueryFnData, TError, TData, TQueryKey>,
220): UnusedSkipTokenOptions<TQueryFnData, TError, TData, TQueryKey> &
221 QueryKeyWithDataTag<TQueryKey, TQueryFnData, TError>
222β
223/**
224 * You can generally pass everything to `queryOptions` that you can also pass to `useQuery`. These options can
225 * be shared across hooks and imperative APIs such as `queryClient.query`. `options.queryKey` is required and
226 * is the query key to generate options for.
227 *
228 * @see {@link useQuery} to run a query with these options.
229 * @param options - The {@link UndefinedInitialDataOptions} to use β everything you can pass to `useQuery`.
230 * @returns The same options object, typed so that `queryKey` carries the inferred data type.
231 * @remarks This is the only overload that accepts `queryFn: skipToken`, shown below.
232 *
233 * @example
234 * A parameterized factory, reused across a hook and an imperative call with the same cache entry:
235 * ```tsx
236 * import { noop, queryOptions, useQuery } from '@tanstack/preact-query'
237 *
238 * export const postOptions = (id: string) =>
239 * queryOptions({
240 * queryKey: ['post', id],
241 * queryFn: () => fetchPost(id),
242 * })
243 *
244 * function Post({ id }: { id: string }) {
245 * const { data, isPending, isError, error } = useQuery(postOptions(id))
246 *
247 * if (isPending) return 'Loading...'
248 * if (isError) return <span>Error: {error.message}</span>
249 *
250 * return <h1>{data.title}</h1>
251 * }
252 *
253 * // `postOptions` also works with imperative APIs like `queryClient.query` β
254 * // see `useQuery` for an example that warms the cache this way before rendering `<Post>`.
255 * const postId = '1'
256 * queryClient.query(postOptions(postId)).catch(noop)
257 * ```
258 *
259 * @example
260 * The same options object works with every API that accepts query options:
261 * ```tsx
262 * import { noop, queryOptions, useQuery } from '@tanstack/preact-query'
263 *
264 * const todosOptions = queryOptions({
265 * queryKey: ['todos'],
266 * queryFn: fetchTodos,
267 * })
268 *
269 * function Todos() {
270 * const { data, isPending, isError, error } = useQuery(todosOptions)
271 *
272 * if (isPending) return 'Loading...'
273 * if (isError) return <span>Error: {error.message}</span>
274 *
275 * return (
276 * <ul>
277 * {data.map((todo) => <li key={todo.id}>{todo.title}</li>)}
278 * </ul>
279 * )
280 * }
281 *
282 * // The same options object works with the imperative APIs too:
283 * queryClient.query(todosOptions).catch(noop)
284 * queryClient.getQueryData(todosOptions.queryKey) // typed as Array<Todo> | undefined
285 * ```
286 *
287 * @example
288 * A factory that disables the query, type safe, until `postId` is set:
289 * ```tsx
290 * import { queryOptions, skipToken, useQuery } from '@tanstack/preact-query'
291 *
292 * export const postOptions = (postId: number | undefined) =>
293 * queryOptions({
294 * queryKey: ['post', postId],
295 * queryFn: postId != null ? () => fetchPost(postId) : skipToken,
296 * })
297 *
298 * function Post({ postId }: { postId: number | undefined }) {
299 * const { data, isLoading, isError, error } = useQuery(postOptions(postId))
300 *
301 * if (postId == null) return 'Select a post'
302 * if (isLoading) return 'Loading...'
303 * if (isError) return <span>Error: {error.message}</span>
304 *
305 * return <h1>{data?.title}</h1>
306 * }
307 * ```
308 */
309export function queryOptions<
310 TQueryFnData = unknown,
311 TError = DefaultError,
312 TData = TQueryFnData,
313 TQueryKey extends QueryKey = QueryKey,
314>(
315 options: UndefinedInitialDataOptions<TQueryFnData, TError, TData, TQueryKey>,
316): UndefinedInitialDataOptions<TQueryFnData, TError, TData, TQueryKey> &
317 QueryKeyWithDataTag<TQueryKey, TQueryFnData, TError>
318β
319export function queryOptions(options: unknown) {
320 return options
321}