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

query-options.ts

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