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

useQuery.ts

296 lines10.5 KB

1import { QueryObserver } from '@tanstack/query-core'
2import { useBaseQuery } from './useBaseQuery'
3import type { DefaultError, QueryClient, QueryKey } from '@tanstack/query-core'
4import type {
5 DefinedInitialDataOptions,
6 UndefinedInitialDataOptions,
7} from './queryOptions'
8import type {
9 DefinedUseQueryResult,
10 UseQueryOptions,
11 UseQueryResult,
12} from './types'
13​
14/**
15 * This overload is selected when `initialData` is known to be defined, so the resulting `data` is typed as never
16 * `undefined` (unless a `select` changes `TData` to include `undefined`). At runtime, `data` is still `undefined`
17 * if `select` throws on its first call.
18 * @param options - The {@link DefinedInitialDataOptions} to use β€” everything you can pass to `useQuery`, with `initialData` known to be defined.
19 * @param queryClient - Use this to use a custom `QueryClient`. Otherwise, the one from the nearest context will
20 * be used.
21 * @returns The current query result, typed so that `status` is `success` or `error` (`status` never
22 * resolves to `pending` in this overload's type, since `initialData` guarantees data upfront). `status` is
23 * `error` if the query has an error from a fetch that failed after its retries or if `select` threw, and
24 * `success` otherwise. `isSuccess`/`isError` are derived booleans for convenience.
25 * @see {@link queryOptions} to share these options between `useQuery` and imperative APIs like `queryClient.query`.
26 * @example
27 * ```tsx
28 * import { useQuery } from '@tanstack/preact-query'
29 *
30 * function Posts() {
31 * // `data` is `Post[]`, never `undefined`, thanks to `initialData` β€” even if a refetch fails,
32 * // so the list stays visible alongside the error.
33 * const { data, isError, error } = useQuery({
34 * queryKey: ['posts'],
35 * queryFn: fetchPosts,
36 * initialData: [],
37 * })
38 *
39 * return (
40 * <div>
41 * {isError ? <span>Error: {error.message}</span> : null}
42 * <ul>
43 * {data.map((post) => <li key={post.id}>{post.title}</li>)}
44 * </ul>
45 * </div>
46 * )
47 * }
48 * ```
49 */
50export function useQuery<
51 TQueryFnData = unknown,
52 TError = DefaultError,
53 TData = TQueryFnData,
54 TQueryKey extends QueryKey = QueryKey,
55>(
56 options: DefinedInitialDataOptions<TQueryFnData, TError, TData, TQueryKey>,
57 queryClient?: QueryClient,
58): DefinedUseQueryResult<TData, TError>
59​
60/**
61 * This overload is selected when `initialData` is omitted, may be `undefined`, or is a function that may
62 * return `undefined`, so the resulting `data` can be `undefined`.
63 * @param options - The {@link UndefinedInitialDataOptions} to use β€” everything you can pass to `useQuery`.
64 * @param queryClient - Use this to use a custom `QueryClient`. Otherwise, the one from the nearest context will
65 * be used.
66 * @returns The current query result. `status` is `error` if the query has an error from a fetch that failed
67 * after its retries or if `select` threw, `success` if the query has cached data (even if `select` returns
68 * `undefined`) or data from `placeholderData`, and `pending` otherwise. `isPending`/`isSuccess`/`isError`
69 * are derived booleans for convenience.
70 * @see {@link queryOptions} to share these options between `useQuery` and imperative APIs like `queryClient.query`.
71 * @example
72 * ```tsx
73 * import { useQuery } from '@tanstack/preact-query'
74 *
75 * function Posts() {
76 * const { status, data, error, isFetching } = useQuery({
77 * queryKey: ['posts'],
78 * queryFn: fetchPosts,
79 * })
80 *
81 * if (status === 'pending') return 'Loading...'
82 * if (status === 'error') return <span>Error: {error.message}</span>
83 *
84 * return (
85 * <div>
86 * <ul>
87 * {data.map((post) => (
88 * <li key={post.id}>{post.title}</li>
89 * ))}
90 * </ul>
91 * <div>{isFetching ? 'Background Updating...' : ' '}</div>
92 * </div>
93 * )
94 * }
95 * ```
96 * @example
97 * The same query, checking `isPending`/`isError` instead of `status` β€” pick whichever reads better to you:
98 * ```tsx
99 * import { useQuery } from '@tanstack/preact-query'
100 *
101 * function Posts() {
102 * const { isPending, isError, data, error } = useQuery({
103 * queryKey: ['posts'],
104 * queryFn: fetchPosts,
105 * })
106 *
107 * if (isPending) return 'Loading...'
108 * if (isError) return <span>Error: {error.message}</span>
109 *
110 * return (
111 * <ul>
112 * {data.map((post) => <li key={post.id}>{post.title}</li>)}
113 * </ul>
114 * )
115 * }
116 * ```
117 */
118export function useQuery<
119 TQueryFnData = unknown,
120 TError = DefaultError,
121 TData = TQueryFnData,
122 TQueryKey extends QueryKey = QueryKey,
123>(
124 options: UndefinedInitialDataOptions<TQueryFnData, TError, TData, TQueryKey>,
125 queryClient?: QueryClient,
126): UseQueryResult<TData, TError>
127​
128/**
129 * Fallback overload for options whose `initialData` presence isn't statically known β€” for example, an
130 * object typed as {@link UseQueryOptions} rather than an object literal. Prefer one of the other overloads
131 * when possible, since they infer whether `data` can be `undefined` from `initialData` directly.
132 * @param options - The {@link UseQueryOptions} to use β€” everything you can pass to `useQuery`.
133 * @param queryClient - Use this to use a custom `QueryClient`. Otherwise, the one from the nearest context will
134 * be used.
135 * @returns The current query result. `status` is `error` if the query has an error from a fetch that failed
136 * after its retries or if `select` threw, `success` if the query has cached data (even if `select` returns
137 * `undefined`) or data from `placeholderData`, and `pending` otherwise. `isPending`/`isSuccess`/`isError`
138 * are derived booleans for convenience.
139 * @see {@link queryOptions} to share these options between `useQuery` and imperative APIs like `queryClient.query`.
140 * @example
141 * ```tsx
142 * import { useQuery } from '@tanstack/preact-query'
143 *
144 * function Posts() {
145 * const { status, data, error, isFetching } = useQuery({
146 * queryKey: ['posts'],
147 * queryFn: fetchPosts,
148 * })
149 *
150 * if (status === 'pending') return 'Loading...'
151 * if (status === 'error') return <span>Error: {error.message}</span>
152 *
153 * return (
154 * <div>
155 * <ul>
156 * {data.map((post) => (
157 * <li key={post.id}>{post.title}</li>
158 * ))}
159 * </ul>
160 * <div>{isFetching ? 'Background Updating...' : ' '}</div>
161 * </div>
162 * )
163 * }
164 * ```
165 * @example
166 * `select` derives whatever `data` a component needs from the cached value, without changing what's
167 * actually stored in the cache β€” the cache still holds the full `Post[]`, but `data` here is a `number`:
168 * ```tsx
169 * import { useQuery } from '@tanstack/preact-query'
170 *
171 * function PostCount() {
172 * const { data, isPending, isError, error } = useQuery({
173 * queryKey: ['posts'],
174 * queryFn: fetchPosts,
175 * select: (posts) => posts.length,
176 * })
177 *
178 * if (isPending) return 'Loading...'
179 * if (isError) return <span>Error: {error.message}</span>
180 *
181 * return <span>{data} posts</span>
182 * }
183 * ```
184 * @example
185 * A dependent query, only enabled once `postId` is set β€” use `isLoading`, not `isPending`, so the
186 * loading state doesn't show while the query is disabled:
187 * ```tsx
188 * import { useQuery } from '@tanstack/preact-query'
189 *
190 * function Post({ postId }: { postId: number | undefined }) {
191 * const { data, isLoading, isError, error } = useQuery({
192 * queryKey: ['post', postId],
193 * queryFn: () => fetchPost(postId!),
194 * enabled: postId != null,
195 * })
196 *
197 * if (postId == null) return 'Select a post'
198 * if (isLoading) return 'Loading...'
199 * if (isError) return <span>Error: {error.message}</span>
200 *
201 * return <h1>{data?.title}</h1>
202 * }
203 * ```
204 * @example
205 * The same dependent query, type safe: `skipToken` disables the query without needing the
206 * non-null assertion above, since `queryFn` is only ever called when `postId` is defined.
207 * `refetch` doesn't work while `queryFn` is `skipToken` β€” use `enabled: false` instead if you
208 * need to trigger the query manually:
209 * ```tsx
210 * import { skipToken, useQuery } from '@tanstack/preact-query'
211 *
212 * function Post({ postId }: { postId: number | undefined }) {
213 * const { data, isLoading, isError, error } = useQuery({
214 * queryKey: ['post', postId],
215 * queryFn: postId != null ? () => fetchPost(postId) : skipToken,
216 * })
217 *
218 * if (postId == null) return 'Select a post'
219 * if (isLoading) return 'Loading...'
220 * if (isError) return <span>Error: {error.message}</span>
221 *
222 * return <h1>{data?.title}</h1>
223 * }
224 * ```
225 * @example
226 * Seeding a detail query from an already-cached list, to skip the loading state. `initialDataUpdatedAt` carries
227 * over the list's own fetch time, so that if you set a `staleTime`, it's measured from when the list was
228 * fetched rather than from now:
229 * ```tsx
230 * import { useQuery, useQueryClient } from '@tanstack/preact-query'
231 *
232 * function Post({ postId }: { postId: number }) {
233 * const queryClient = useQueryClient()
234 *
235 * const { data, isError, error } = useQuery({
236 * queryKey: ['post', postId],
237 * queryFn: () => fetchPost(postId),
238 * initialData: () =>
239 * queryClient
240 * .getQueryData<Array<Post>>(['posts'])
241 * ?.find((post) => post.id === postId),
242 * initialDataUpdatedAt: () =>
243 * queryClient.getQueryState(['posts'])?.dataUpdatedAt,
244 * })
245 *
246 * if (isError) return <span>Error: {error.message}</span>
247 *
248 * return <h1>{data?.title}</h1>
249 * }
250 * ```
251 * @example
252 * Paginated data, keeping the previous page's data visible while the next page loads:
253 * ```tsx
254 * import { keepPreviousData, useQuery } from '@tanstack/preact-query'
255 * import { useState } from 'preact/hooks'
256 *
257 * function Posts() {
258 * const [page, setPage] = useState(0)
259 *
260 * const { data, isPlaceholderData, isError, error } = useQuery({
261 * queryKey: ['posts', page],
262 * queryFn: () => fetchPosts(page),
263 * placeholderData: keepPreviousData,
264 * })
265 *
266 * if (isError) return <span>Error: {error.message}</span>
267 *
268 * return (
269 * <div>
270 * <ul>
271 * {data?.map((post) => <li key={post.id}>{post.title}</li>)}
272 * </ul>
273 * <button
274 * disabled={isPlaceholderData}
275 * onClick={() => setPage((old) => old + 1)}
276 * >
277 * Next Page
278 * </button>
279 * </div>
280 * )
281 * }
282 * ```
283 */
284export function useQuery<
285 TQueryFnData = unknown,
286 TError = DefaultError,
287 TData = TQueryFnData,
288 TQueryKey extends QueryKey = QueryKey,
289>(
290 options: UseQueryOptions<TQueryFnData, TError, TData, TQueryKey>,
291 queryClient?: QueryClient,
292): UseQueryResult<TData, TError>
293​
294export function useQuery(options: UseQueryOptions, queryClient?: QueryClient) {
295 return useBaseQuery(options, QueryObserver, queryClient)