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` is never `undefined` (unless
17 * a `select` changes `TData` to include `undefined`).
18 *
19 * @see {@link queryOptions} to share these options between `useQuery` and imperative APIs like `queryClient.query`.
20 * @param options - The {@link DefinedInitialDataOptions} to use β everything you can pass to `useQuery`, with `initialData` set.
21 * @param queryClient - Use this to use a custom `QueryClient`. Otherwise, the one from the nearest context will
22 * be used.
23 * @returns The current query result, typed so that `status` is `success` β or `error` if a fetch attempt
24 * fails while keeping the existing data (`status` never resolves to `pending` in this overload's type,
25 * since `initialData` guarantees data upfront). `isSuccess`/`isError` are derived booleans for convenience.
26 *
27 * @example
28 * ```tsx
29 * import { useQuery } from '@tanstack/react-query'
30 *
31 * function Posts() {
32 * // `data` is `Post[]`, never `undefined`, thanks to `initialData` β even if a refetch fails,
33 * // so the list stays visible alongside the error.
34 * const { data, isError, error } = useQuery({
35 * queryKey: ['posts'],
36 * queryFn: fetchPosts,
37 * initialData: [],
38 * })
39 *
40 * return (
41 * <div>
42 * {isError ? <span>Error: {error.message}</span> : null}
43 * <ul>
44 * {data.map((post) => <li key={post.id}>{post.title}</li>)}
45 * </ul>
46 * </div>
47 * )
48 * }
49 * ```
50 */
51export function useQuery<
52 TQueryFnData = unknown,
53 TError = DefaultError,
54 TData = TQueryFnData,
55 TQueryKey extends QueryKey = QueryKey,
56>(
57 options: DefinedInitialDataOptions<TQueryFnData, TError, TData, TQueryKey>,
58 queryClient?: QueryClient,
59): DefinedUseQueryResult<TData, TError>
60β
61/**
62 * @see {@link queryOptions} to share these options between `useQuery` and imperative APIs like `queryClient.query`.
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 `pending` if there is no cached data to display, `error` if
67 * the last fetch attempt failed, or `success` if the query has data to display. `isPending`/`isSuccess`/`isError`
68 * are derived booleans for convenience.
69 *
70 * @example
71 * ```tsx
72 * import { useQuery } from '@tanstack/react-query'
73 *
74 * function Posts() {
75 * const { status, data, error, isFetching } = useQuery({
76 * queryKey: ['posts'],
77 * queryFn: fetchPosts,
78 * })
79 *
80 * if (status === 'pending') return 'Loading...'
81 * if (status === 'error') return <span>Error: {error.message}</span>
82 *
83 * return (
84 * <div>
85 * <ul>
86 * {data.map((post) => (
87 * <li key={post.id}>{post.title}</li>
88 * ))}
89 * </ul>
90 * <div>{isFetching ? 'Background Updating...' : ' '}</div>
91 * </div>
92 * )
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/react-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 * @see {@link queryOptions} to share these options between `useQuery` and imperative APIs like `queryClient.query`.
130 * @param options - The {@link UseQueryOptions} to use β everything you can pass to `useQuery`.
131 * @param queryClient - Use this to use a custom `QueryClient`. Otherwise, the one from the nearest context will
132 * be used.
133 * @returns The current query result. `status` is `pending` if there is no cached data to display, `error` if
134 * the last fetch attempt failed, or `success` if the query has data to display. `isPending`/`isSuccess`/`isError`
135 * are derived booleans for convenience.
136 *
137 * @example
138 * ```tsx
139 * import { useQuery } from '@tanstack/react-query'
140 *
141 * function Posts() {
142 * const { status, data, error, isFetching } = useQuery({
143 * queryKey: ['posts'],
144 * queryFn: fetchPosts,
145 * })
146 *
147 * if (status === 'pending') return 'Loading...'
148 * if (status === 'error') return <span>Error: {error.message}</span>
149 *
150 * return (
151 * <div>
152 * <ul>
153 * {data.map((post) => (
154 * <li key={post.id}>{post.title}</li>
155 * ))}
156 * </ul>
157 * <div>{isFetching ? 'Background Updating...' : ' '}</div>
158 * </div>
159 * )
160 * }
161 * ```
162 *
163 * @example
164 * `select` derives whatever `data` a component needs from the cached value, without changing what's
165 * actually stored in the cache β the cache still holds the full `Post[]`, but `data` here is a `number`:
166 * ```tsx
167 * import { useQuery } from '@tanstack/react-query'
168 *
169 * function PostCount() {
170 * const { data, isPending, isError, error } = useQuery({
171 * queryKey: ['posts'],
172 * queryFn: fetchPosts,
173 * select: (posts) => posts.length,
174 * })
175 *
176 * if (isPending) return 'Loading...'
177 * if (isError) return <span>Error: {error.message}</span>
178 *
179 * return <span>{data} posts</span>
180 * }
181 * ```
182 *
183 * @example
184 * A dependent query, only enabled once `postId` is set β use `isLoading`, not `isPending`, so the
185 * loading state doesn't show while the query is disabled:
186 * ```tsx
187 * import { useQuery } from '@tanstack/react-query'
188 *
189 * function Post({ postId }: { postId: number | undefined }) {
190 * const { data, isLoading, isError, error } = useQuery({
191 * queryKey: ['post', postId],
192 * queryFn: () => fetchPost(postId!),
193 * enabled: postId != null,
194 * })
195 *
196 * if (postId == null) return 'Select a post'
197 * if (isLoading) return 'Loading...'
198 * if (isError) return <span>Error: {error.message}</span>
199 *
200 * return <h1>{data?.title}</h1>
201 * }
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/react-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 *
226 * @example
227 * Seeding a detail query from an already-cached list, to skip the loading state. `initialDataUpdatedAt` carries
228 * over the list's own fetch time, so that if you set a `staleTime`, it's measured from when the list was
229 * fetched rather than from now:
230 * ```tsx
231 * import { useQuery, useQueryClient } from '@tanstack/react-query'
232 *
233 * function Post({ postId }: { postId: number }) {
234 * const queryClient = useQueryClient()
235 *
236 * const { data, isError, error } = useQuery({
237 * queryKey: ['post', postId],
238 * queryFn: () => fetchPost(postId),
239 * initialData: () =>
240 * queryClient
241 * .getQueryData<Array<Post>>(['posts'])
242 * ?.find((post) => post.id === postId),
243 * initialDataUpdatedAt: () =>
244 * queryClient.getQueryState(['posts'])?.dataUpdatedAt,
245 * })
246 *
247 * if (isError) return <span>Error: {error.message}</span>
248 *
249 * return <h1>{data?.title}</h1>
250 * }
251 * ```
252 *
253 * @example
254 * Paginated data, keeping the previous page's data visible while the next page loads:
255 * ```tsx
256 * import { keepPreviousData, useQuery } from '@tanstack/react-query'
257 * import { useState } from 'react'
258 *
259 * function Posts() {
260 * const [page, setPage] = useState(0)
261 *
262 * const { data, isPlaceholderData, isError, error } = useQuery({
263 * queryKey: ['posts', page],
264 * queryFn: () => fetchPosts(page),
265 * placeholderData: keepPreviousData,
266 * })
267 *
268 * if (isError) return <span>Error: {error.message}</span>
269 *
270 * return (
271 * <div>
272 * <ul>
273 * {data?.map((post) => <li key={post.id}>{post.title}</li>)}
274 * </ul>
275 * <button
276 * disabled={isPlaceholderData}
277 * onClick={() => setPage((old) => old + 1)}
278 * >
279 * Next Page
280 * </button>
281 * </div>
282 * )
283 * }
284 * ```
285 */
286export function useQuery<
287 TQueryFnData = unknown,
288 TError = DefaultError,
289 TData = TQueryFnData,
290 TQueryKey extends QueryKey = QueryKey,
291>(
292 options: UseQueryOptions<TQueryFnData, TError, TData, TQueryKey>,
293 queryClient?: QueryClient,
294): UseQueryResult<TData, TError>
295β
296export function useQuery(options: UseQueryOptions, queryClient?: QueryClient) {
297 return useBaseQuery(options, QueryObserver, queryClient)
298}