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

queryOptions.ts

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