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

query-options.ts

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