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

useQuery.ts

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