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

queryOptions.ts

283 lines10.2 KB

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