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