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

queryOptions.ts

250 lines10.0 KB

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