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

useQuery.ts

297 lines10.5 KB

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 DefinedInitialDataOptions,
7 UndefinedInitialDataOptions,
8} from './queryOptions'
9import type {
10 DefinedUseQueryResult,
11 UseQueryOptions,
12 UseQueryResult,
13} from './types'
14​
15/**
16 * This overload is selected when `initialData` is known to be defined, so the resulting `data` is typed as never
17 * `undefined` (unless a `select` changes `TData` to include `undefined`). At runtime, `data` is still `undefined`
18 * if `select` throws on its first call.
19 * @param options - The {@link DefinedInitialDataOptions} to use β€” everything you can pass to `useQuery`, with `initialData` known to be defined.
20 * @param queryClient - Use this to use a custom `QueryClient`. Otherwise, the one from the nearest context will
21 * be used.
22 * @returns The current query result, typed so that `status` is `success` or `error` (`status` never
23 * resolves to `pending` in this overload's type, since `initialData` guarantees data upfront). `status` is
24 * `error` if the query has an error from a fetch that failed after its retries or if `select` threw, and
25 * `success` otherwise. `isSuccess`/`isError` are derived booleans for convenience.
26 * @see {@link queryOptions} to share these options between `useQuery` and imperative APIs like `queryClient.query`.
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 * This overload is selected when `initialData` is omitted, may be `undefined`, or is a function that may
63 * return `undefined`, so the resulting `data` can be `undefined`.
64 * @param options - The {@link UndefinedInitialDataOptions} to use β€” everything you can pass to `useQuery`.
65 * @param queryClient - Use this to use a custom `QueryClient`. Otherwise, the one from the nearest context will
66 * be used.
67 * @returns The current query result. `status` is `error` if the query has an error from a fetch that failed
68 * after its retries or if `select` threw, `success` if the query has cached data (even if `select` returns
69 * `undefined`) or data from `placeholderData`, and `pending` otherwise. `isPending`/`isSuccess`/`isError`
70 * are derived booleans for convenience.
71 * @see {@link queryOptions} to share these options between `useQuery` and imperative APIs like `queryClient.query`.
72 * @example
73 * ```tsx
74 * import { useQuery } from '@tanstack/react-query'
75 *
76 * function Posts() {
77 * const { status, data, error, isFetching } = useQuery({
78 * queryKey: ['posts'],
79 * queryFn: fetchPosts,
80 * })
81 *
82 * if (status === 'pending') return 'Loading...'
83 * if (status === 'error') return <span>Error: {error.message}</span>
84 *
85 * return (
86 * <div>
87 * <ul>
88 * {data.map((post) => (
89 * <li key={post.id}>{post.title}</li>
90 * ))}
91 * </ul>
92 * <div>{isFetching ? 'Background Updating...' : ' '}</div>
93 * </div>
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 */
119export function useQuery<
120 TQueryFnData = unknown,
121 TError = DefaultError,
122 TData = TQueryFnData,
123 TQueryKey extends QueryKey = QueryKey,
124>(
125 options: UndefinedInitialDataOptions<TQueryFnData, TError, TData, TQueryKey>,
126 queryClient?: QueryClient,
127): UseQueryResult<TData, TError>
128​
129/**
130 * Fallback overload for options whose `initialData` presence isn't statically known β€” for example, an
131 * object typed as {@link UseQueryOptions} rather than an object literal. Prefer one of the other overloads
132 * when possible, since they infer whether `data` can be `undefined` from `initialData` directly.
133 * @param options - The {@link UseQueryOptions} to use β€” everything you can pass to `useQuery`.
134 * @param queryClient - Use this to use a custom `QueryClient`. Otherwise, the one from the nearest context will
135 * be used.
136 * @returns The current query result. `status` is `error` if the query has an error from a fetch that failed
137 * after its retries or if `select` threw, `success` if the query has cached data (even if `select` returns
138 * `undefined`) or data from `placeholderData`, and `pending` otherwise. `isPending`/`isSuccess`/`isError`
139 * are derived booleans for convenience.
140 * @see {@link queryOptions} to share these options between `useQuery` and imperative APIs like `queryClient.query`.
141 * @example
142 * ```tsx
143 * import { useQuery } from '@tanstack/react-query'
144 *
145 * function Posts() {
146 * const { status, data, error, isFetching } = useQuery({
147 * queryKey: ['posts'],
148 * queryFn: fetchPosts,
149 * })
150 *
151 * if (status === 'pending') return 'Loading...'
152 * if (status === 'error') return <span>Error: {error.message}</span>
153 *
154 * return (
155 * <div>
156 * <ul>
157 * {data.map((post) => (
158 * <li key={post.id}>{post.title}</li>
159 * ))}
160 * </ul>
161 * <div>{isFetching ? 'Background Updating...' : ' '}</div>
162 * </div>
163 * )
164 * }
165 * ```
166 * @example
167 * `select` derives whatever `data` a component needs from the cached value, without changing what's
168 * actually stored in the cache β€” the cache still holds the full `Post[]`, but `data` here is a `number`:
169 * ```tsx
170 * import { useQuery } from '@tanstack/react-query'
171 *
172 * function PostCount() {
173 * const { data, isPending, isError, error } = useQuery({
174 * queryKey: ['posts'],
175 * queryFn: fetchPosts,
176 * select: (posts) => posts.length,
177 * })
178 *
179 * if (isPending) return 'Loading...'
180 * if (isError) return <span>Error: {error.message}</span>
181 *
182 * return <span>{data} posts</span>
183 * }
184 * ```
185 * @example
186 * A dependent query, only enabled once `postId` is set β€” use `isLoading`, not `isPending`, so the
187 * loading state doesn't show while the query is disabled:
188 * ```tsx
189 * import { useQuery } from '@tanstack/react-query'
190 *
191 * function Post({ postId }: { postId: number | undefined }) {
192 * const { data, isLoading, isError, error } = useQuery({
193 * queryKey: ['post', postId],
194 * queryFn: () => fetchPost(postId!),
195 * enabled: postId != null,
196 * })
197 *
198 * if (postId == null) return 'Select a post'
199 * if (isLoading) return 'Loading...'
200 * if (isError) return <span>Error: {error.message}</span>
201 *
202 * return <h1>{data?.title}</h1>
203 * }
204 * ```
205 * @example
206 * The same dependent query, type safe: `skipToken` disables the query without needing the
207 * non-null assertion above, since `queryFn` is only ever called when `postId` is defined.
208 * `refetch` doesn't work while `queryFn` is `skipToken` β€” use `enabled: false` instead if you
209 * need to trigger the query manually:
210 * ```tsx
211 * import { skipToken, useQuery } from '@tanstack/react-query'
212 *
213 * function Post({ postId }: { postId: number | undefined }) {
214 * const { data, isLoading, isError, error } = useQuery({
215 * queryKey: ['post', postId],
216 * queryFn: postId != null ? () => fetchPost(postId) : skipToken,
217 * })
218 *
219 * if (postId == null) return 'Select a post'
220 * if (isLoading) return 'Loading...'
221 * if (isError) return <span>Error: {error.message}</span>
222 *
223 * return <h1>{data?.title}</h1>
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 * @example
253 * Paginated data, keeping the previous page's data visible while the next page loads:
254 * ```tsx
255 * import { keepPreviousData, useQuery } from '@tanstack/react-query'
256 * import { useState } from 'react'
257 *
258 * function Posts() {
259 * const [page, setPage] = useState(0)
260 *
261 * const { data, isPlaceholderData, isError, error } = useQuery({
262 * queryKey: ['posts', page],
263 * queryFn: () => fetchPosts(page),
264 * placeholderData: keepPreviousData,
265 * })
266 *
267 * if (isError) return <span>Error: {error.message}</span>
268 *
269 * return (
270 * <div>
271 * <ul>
272 * {data?.map((post) => <li key={post.id}>{post.title}</li>)}
273 * </ul>
274 * <button
275 * disabled={isPlaceholderData}
276 * onClick={() => setPage((old) => old + 1)}
277 * >
278 * Next Page
279 * </button>
280 * </div>
281 * )
282 * }
283 * ```
284 */
285export function useQuery<
286 TQueryFnData = unknown,
287 TError = DefaultError,
288 TData = TQueryFnData,
289 TQueryKey extends QueryKey = QueryKey,
290>(
291 options: UseQueryOptions<TQueryFnData, TError, TData, TQueryKey>,
292 queryClient?: QueryClient,
293): UseQueryResult<TData, TError>
294​
295export function useQuery(options: UseQueryOptions, queryClient?: QueryClient) {
296 return useBaseQuery(options, QueryObserver, queryClient)