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