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

queryOptions.ts

254 lines10.3 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 `initialData` is omitted, may be
16 * `undefined`, or is a function that may return `undefined` β€” `data` may be `undefined` while the query is
17 * `pending`.
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 `queryFn` is not `skipToken` and
44 * `initialData` is omitted, may be `undefined`, or is a function that may return `undefined` β€” same as
45 * {@link UndefinedInitialDataOptions}, but `queryFn` may not be `skipToken`.
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 `initialData` is omitted, may
62 * be `undefined`, or is a function that may return `undefined`. If you don't intend to run the query yet,
63 * set `enabled: false` β€” omitting `queryFn` alone still triggers a fetch that fails with "Missing queryFn"
64 * unless `enabled` is `false` or a default query function has been defined. A default query function only
65 * supplies `queryFn`; it doesn't defer the fetch on its own.
66 */
67 queryFn?: Exclude<
68 UseQueryOptions<TQueryFnData, TError, TData, TQueryKey>['queryFn'],
69 SkipToken | undefined
70 >
72​
73/**
74 * The options accepted by the `queryOptions` overload selected when `initialData` is known to be defined β€”
75 * `data` is never `undefined` (unless a `select` changes `TData` to include `undefined`).
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 known to be defined, so the resulting `data` is never
111 * `undefined` (unless a `select` changes `TData` to include `undefined`).
112 * @param options - The {@link DefinedInitialDataOptions} to use β€” everything you can pass to `useQuery`, with `initialData` known to be defined.
113 * @returns The same options object, typed so that `queryKey` carries the inferred data type.
114 * @see {@link useQuery} to run a query with these options.
115 * @see [The Query Options API](https://tkdodo.eu/blog/the-query-options-api) for more on this pattern.
116 * @example
117 * ```tsx
118 * import { queryOptions, useQuery } from '@tanstack/preact-query'
119 *
120 * export const postsOptions = queryOptions({
121 * queryKey: ['posts'],
122 * queryFn: fetchPosts,
123 * initialData: [],
124 * })
125 *
126 * function Posts() {
127 * // `data` is `Post[]`, never `undefined`, thanks to `initialData` β€” even if a refetch fails,
128 * // so the list stays visible alongside the error.
129 * const { data, isError, error } = useQuery(postsOptions)
130 *
131 * return (
132 * <div>
133 * {isError ? <span>Error: {error.message}</span> : null}
134 * <ul>
135 * {data.map((post) => <li key={post.id}>{post.title}</li>)}
136 * </ul>
137 * </div>
138 * )
139 * }
140 * ```
141 */
142export function queryOptions<
143 TQueryFnData = unknown,
144 TError = DefaultError,
145 TData = TQueryFnData,
146 TQueryKey extends QueryKey = QueryKey,
147>(
148 options: DefinedInitialDataOptions<TQueryFnData, TError, TData, TQueryKey>,
149): DefinedInitialDataOptions<TQueryFnData, TError, TData, TQueryKey> &
150 QueryKeyWithDataTag<TQueryKey, TQueryFnData, TError>
151​
152/**
153 * You can generally pass everything to `queryOptions` that you can also pass to `useQuery`. These options can
154 * be shared across hooks and imperative APIs such as `queryClient.query`. `options.queryKey` is required and
155 * is the query key to generate options for.
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 * @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 * @example
161 * A parameterized factory, so the same options object can be reused per `id`:
162 * ```tsx
163 * import { queryOptions, useQuery } from '@tanstack/preact-query'
164 *
165 * export const postOptions = (id: string) =>
166 * queryOptions({
167 * queryKey: ['post', id],
168 * queryFn: () => fetchPost(id),
169 * })
170 *
171 * function Post({ id }: { id: string }) {
172 * const { data, isPending, isError, error } = useQuery(postOptions(id))
173 *
174 * if (isPending) return 'Loading...'
175 * if (isError) return <span>Error: {error.message}</span>
176 *
177 * return <h1>{data.title}</h1>
178 * }
179 * ```
180 */
181export function queryOptions<
182 TQueryFnData = unknown,
183 TError = DefaultError,
184 TData = TQueryFnData,
185 TQueryKey extends QueryKey = QueryKey,
186>(
187 options: UnusedSkipTokenOptions<TQueryFnData, TError, TData, TQueryKey>,
188): UnusedSkipTokenOptions<TQueryFnData, TError, TData, TQueryKey> &
189 QueryKeyWithDataTag<TQueryKey, TQueryFnData, TError>
190​
191/**
192 * You can generally pass everything to `queryOptions` that you can also pass to `useQuery`. These options can
193 * be shared across hooks and imperative APIs such as `queryClient.query`. `options.queryKey` is required and
194 * is the query key to generate options for.
195 * @param options - The {@link UndefinedInitialDataOptions} to use β€” everything you can pass to `useQuery`.
196 * @returns The same options object, typed so that `queryKey` carries the inferred data type.
197 * @remarks This is the only overload that accepts `queryFn: skipToken`, shown below.
198 * @see {@link useQuery} to run a query with these options.
199 * @see [The Query Options API](https://tkdodo.eu/blog/the-query-options-api) for more on this pattern.
200 * @example
201 * A parameterized factory, so the same options object can be reused per `id`:
202 * ```tsx
203 * import { queryOptions, useQuery } from '@tanstack/preact-query'
204 *
205 * export const postOptions = (id: string) =>
206 * queryOptions({
207 * queryKey: ['post', id],
208 * queryFn: () => fetchPost(id),
209 * })
210 *
211 * function Post({ id }: { id: string }) {
212 * const { data, isPending, isError, error } = useQuery(postOptions(id))
213 *
214 * if (isPending) return 'Loading...'
215 * if (isError) return <span>Error: {error.message}</span>
216 *
217 * return <h1>{data.title}</h1>
218 * }
219 * ```
220 * @example
221 * A factory that disables the query, type safe, until `postId` is set:
222 * ```tsx
223 * import { queryOptions, skipToken, useQuery } from '@tanstack/preact-query'
224 *
225 * export const postOptions = (postId: number | undefined) =>
226 * queryOptions({
227 * queryKey: ['post', postId],
228 * queryFn: postId != null ? () => fetchPost(postId) : skipToken,
229 * })
230 *
231 * function Post({ postId }: { postId: number | undefined }) {
232 * const { data, isLoading, isError, error } = useQuery(postOptions(postId))
233 *
234 * if (postId == null) return 'Select a post'
235 * if (isLoading) return 'Loading...'
236 * if (isError) return <span>Error: {error.message}</span>
237 *
238 * return <h1>{data?.title}</h1>
239 * }
240 * ```
241 */
242export function queryOptions<
243 TQueryFnData = unknown,
244 TError = DefaultError,
245 TData = TQueryFnData,
246 TQueryKey extends QueryKey = QueryKey,
247>(
248 options: UndefinedInitialDataOptions<TQueryFnData, TError, TData, TQueryKey>,
249): UndefinedInitialDataOptions<TQueryFnData, TError, TData, TQueryKey> &
250 QueryKeyWithDataTag<TQueryKey, TQueryFnData, TError>
251​
252export function queryOptions(options: unknown) {
253 return options