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

query-options.ts

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