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

queryOptions.ts

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