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

query-options.ts

276 lines9.9 KB

1import type {
2 DefaultError,
3 InitialDataFunction,
4 NonUndefinedGuard,
5 OmitKeyof,
6 QueryKey,
7 QueryKeyWithDataTag,
8 SkipToken,
9} from '@tanstack/query-core'
10import type { CreateQueryOptions } from './types'
11​
12/**
13 * The options accepted by the `queryOptions` overload selected when no `initialData` is set β€” `data` may be
14 * `undefined` while the query is `pending`.
15 *
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 *
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 CreateQueryOptions<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 CreateQueryOptions<TQueryFnData, TError, TData, TQueryKey>['queryFn'],
66 SkipToken | undefined
67 >
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 *
74 * @template TQueryFnData - The type your `queryFn` resolves to.
75 * @template TError - The type of errors your `queryFn` may throw.
76 * @template TData - The type `data` ends up as after `select` runs.
77 * @template TQueryKey - The type of your `queryKey`.
78 */
79export type DefinedInitialDataOptions<
80 TQueryFnData = unknown,
81 TError = DefaultError,
82 TData = TQueryFnData,
83 TQueryKey extends QueryKey = QueryKey,
84> = CreateQueryOptions<TQueryFnData, TError, TData, TQueryKey> & {
85 initialData:
86 | NonUndefinedGuard<TQueryFnData>
87 | (() => NonUndefinedGuard<TQueryFnData>)
89​
90/**
91 * You can generally pass everything to `queryOptions` that you can also pass to `injectQuery`. These options
92 * can be shared across functions and imperative APIs such as `queryClient.query`. `options.queryKey` is
93 * required and is the query key to generate options for.
94 *
95 * This overload is selected when `initialData` is set, so the resulting `data` is never `undefined` (unless
96 * a `select` changes `TData` to include `undefined`).
97 *
98 * @see {@link injectQuery} to run a query with these options.
99 * @see [The Query Options API](https://tkdodo.eu/blog/the-query-options-api) for more on this pattern.
100 * @param options - The {@link DefinedInitialDataOptions} to use β€” everything you can pass to `injectQuery`,
101 * with `initialData` set.
102 * @returns The same options object, typed so that `queryKey` carries the inferred data type.
103 *
104 * @example
105 * ```angular-ts
106 * import { queryOptions, injectQuery } from '@tanstack/angular-query'
107 *
108 * export const postsOptions = queryOptions({
109 * queryKey: ['posts'],
110 * queryFn: fetchPosts,
111 * initialData: [],
112 * })
113 *
114 * @Component({
115 * selector: 'posts',
116 * template: `
117 * <!-- `postsQuery.data()` is never `undefined`, thanks to `initialData` β€” even if a refetch
118 * fails, so the list stays visible alongside the error. -->
119 * @if (postsQuery.isError()) {
120 * <span>Error: {{ postsQuery.error()?.message }}</span>
121 * }
122 * <ul>
123 * @for (post of postsQuery.data(); track post.id) {
124 * <li>{{ post.title }}</li>
125 * }
126 * </ul>
127 * `,
128 * })
129 * export class Posts {
130 * readonly postsQuery = injectQuery(() => postsOptions)
131 * }
132 * ```
133 */
134export function queryOptions<
135 TQueryFnData = unknown,
136 TError = DefaultError,
137 TData = TQueryFnData,
138 TQueryKey extends QueryKey = QueryKey,
139>(
140 options: DefinedInitialDataOptions<TQueryFnData, TError, TData, TQueryKey>,
141): DefinedInitialDataOptions<TQueryFnData, TError, TData, TQueryKey> &
142 QueryKeyWithDataTag<TQueryKey, TQueryFnData, TError>
143​
144/**
145 * You can generally pass everything to `queryOptions` that you can also pass to `injectQuery`. These options
146 * can be shared across functions and imperative APIs such as `queryClient.query`. `options.queryKey` is
147 * required and is the query key to generate options for.
148 *
149 * @see {@link injectQuery} to run a query with these options.
150 * @see [The Query Options API](https://tkdodo.eu/blog/the-query-options-api) for more on this pattern.
151 * @param options - The {@link UnusedSkipTokenOptions} to use β€” everything you can pass to `injectQuery`.
152 * @returns The same options object, typed so that `queryKey` carries the inferred data type.
153 *
154 * @example
155 * A parameterized factory, so the same options object can be reused per `id`:
156 * ```angular-ts
157 * import { queryOptions, injectQuery } from '@tanstack/angular-query'
158 *
159 * export const postOptions = (id: string) =>
160 * queryOptions({
161 * queryKey: ['post', id],
162 * queryFn: () => fetchPost(id),
163 * })
164 *
165 * @Component({
166 * selector: 'post',
167 * template: `
168 * @if (postQuery.isPending()) {
169 * Loading...
170 * } @else if (postQuery.isError()) {
171 * <span>Error: {{ postQuery.error()?.message }}</span>
172 * } @else {
173 * <h1>{{ postQuery.data().title }}</h1>
174 * }
175 * `,
176 * })
177 * export class Post {
178 * readonly id = signal('1')
179 * readonly postQuery = injectQuery(() => postOptions(this.id()))
180 * }
181 * ```
182 */
183export function queryOptions<
184 TQueryFnData = unknown,
185 TError = DefaultError,
186 TData = TQueryFnData,
187 TQueryKey extends QueryKey = QueryKey,
188>(
189 options: UnusedSkipTokenOptions<TQueryFnData, TError, TData, TQueryKey>,
190): UnusedSkipTokenOptions<TQueryFnData, TError, TData, TQueryKey> &
191 QueryKeyWithDataTag<TQueryKey, TQueryFnData, TError>
192​
193/**
194 * You can generally pass everything to `queryOptions` that you can also pass to `injectQuery`. These options
195 * can be shared across functions and imperative APIs such as `queryClient.query`. `options.queryKey` is
196 * required and is the query key to generate options for.
197 *
198 * @see {@link injectQuery} to run a query with these options.
199 * @see [The Query Options API](https://tkdodo.eu/blog/the-query-options-api) for more on this pattern.
200 * @param options - The {@link UndefinedInitialDataOptions} to use β€” everything you can pass to `injectQuery`.
201 * @returns The same options object, typed so that `queryKey` carries the inferred data type.
202 * @remarks This is the only overload that accepts `queryFn: skipToken`, shown below.
203 *
204 * @example
205 * A parameterized factory, so the same options object can be reused per `id`:
206 * ```angular-ts
207 * import { queryOptions, injectQuery } from '@tanstack/angular-query'
208 *
209 * export const postOptions = (id: string) =>
210 * queryOptions({
211 * queryKey: ['post', id],
212 * queryFn: () => fetchPost(id),
213 * })
214 *
215 * @Component({
216 * selector: 'post',
217 * template: `
218 * @if (postQuery.isPending()) {
219 * Loading...
220 * } @else if (postQuery.isError()) {
221 * <span>Error: {{ postQuery.error()?.message }}</span>
222 * } @else {
223 * <h1>{{ postQuery.data().title }}</h1>
224 * }
225 * `,
226 * })
227 * export class Post {
228 * readonly id = signal('1')
229 * readonly postQuery = injectQuery(() => postOptions(this.id()))
230 * }
231 * ```
232 *
233 * @example
234 * A factory that disables the query, type safe, until `postId` is set:
235 * ```angular-ts
236 * import { queryOptions, skipToken, injectQuery } from '@tanstack/angular-query'
237 *
238 * export const postOptions = (postId: number | undefined) =>
239 * queryOptions({
240 * queryKey: ['post', postId],
241 * queryFn: postId != null ? () => fetchPost(postId) : skipToken,
242 * })
243 *
244 * @Component({
245 * selector: 'post',
246 * template: `
247 * @if (postId() == null) {
248 * Select a post
249 * } @else if (postQuery.isPending()) {
250 * Loading...
251 * } @else if (postQuery.isError()) {
252 * <span>Error: {{ postQuery.error()?.message }}</span>
253 * } @else {
254 * <h1>{{ postQuery.data().title }}</h1>
255 * }
256 * `,
257 * })
258 * export class Post {
259 * readonly postId = signal<number | undefined>(undefined)
260 * readonly postQuery = injectQuery(() => postOptions(this.postId()))
261 * }
262 * ```
263 */
264export function queryOptions<
265 TQueryFnData = unknown,
266 TError = DefaultError,
267 TData = TQueryFnData,
268 TQueryKey extends QueryKey = QueryKey,
269>(
270 options: UndefinedInitialDataOptions<TQueryFnData, TError, TData, TQueryKey>,
271): UndefinedInitialDataOptions<TQueryFnData, TError, TData, TQueryKey> &
272 QueryKeyWithDataTag<TQueryKey, TQueryFnData, TError>
273​
274export function queryOptions(options: unknown) {
275 return options