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

query-options.ts

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