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

useQuery.ts

293 lines9.3 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 set, so the resulting `data` is never `undefined`.
17 *
18 * @see {@link queryOptions} to share these options between `useQuery` and imperative APIs like `queryClient.query`.
19 * @param options - The {@link DefinedInitialDataOptions} to use β€” everything you can pass to `useQuery`, with `initialData` set.
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` if a fetch attempt
23 * fails while keeping the existing data (`status` never resolves to `pending` in this overload's type,
24 * since `initialData` guarantees data upfront). `isSuccess`/`isError` are derived booleans for convenience.
25 *
26 * @example
27 * ```tsx
28 * import { useQuery } from '@tanstack/react-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 * @see {@link queryOptions} to share these options between `useQuery` and imperative APIs like `queryClient.query`.
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 *
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 *
95 * @example
96 * The same query, checking `isPending`/`isError` instead of `status` β€” pick whichever reads better to you:
97 * ```tsx
98 * import { useQuery } from '@tanstack/react-query'
99 *
100 * function Posts() {
101 * const { isPending, isError, data, error } = useQuery({
102 * queryKey: ['posts'],
103 * queryFn: fetchPosts,
104 * })
105 *
106 * if (isPending) return 'Loading...'
107 * if (isError) return <span>Error: {error.message}</span>
108 *
109 * return (
110 * <ul>
111 * {data.map((post) => <li key={post.id}>{post.title}</li>)}
112 * </ul>
113 * )
114 * }
115 * ```
116 */
117export function useQuery<
118 TQueryFnData = unknown,
119 TError = DefaultError,
120 TData = TQueryFnData,
121 TQueryKey extends QueryKey = QueryKey,
122>(
123 options: UndefinedInitialDataOptions<TQueryFnData, TError, TData, TQueryKey>,
124 queryClient?: QueryClient,
125): UseQueryResult<TData, TError>
126​
127/**
128 * @see {@link queryOptions} to share these options between `useQuery` and imperative APIs like `queryClient.query`.
129 * @param options - The {@link UseQueryOptions} to use β€” everything you can pass to `useQuery`.
130 * @param queryClient - Use this to use a custom `QueryClient`. Otherwise, the one from the nearest context will
131 * be used.
132 * @returns The current query result. `status` is `pending` if there is no cached data to display, `error` if
133 * the last fetch attempt failed, or `success` if the query has data to display. `isPending`/`isSuccess`/`isError`
134 * are derived booleans for convenience.
135 *
136 * @example
137 * ```tsx
138 * import { useQuery } from '@tanstack/react-query'
139 *
140 * function Posts() {
141 * const { status, data, error, isFetching } = useQuery({
142 * queryKey: ['posts'],
143 * queryFn: fetchPosts,
144 * })
145 *
146 * if (status === 'pending') return 'Loading...'
147 * if (status === 'error') return <span>Error: {error.message}</span>
148 *
149 * return (
150 * <div>
151 * <ul>
152 * {data.map((post) => (
153 * <li key={post.id}>{post.title}</li>
154 * ))}
155 * </ul>
156 * <div>{isFetching ? 'Background Updating...' : ' '}</div>
157 * </div>
158 * )
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 *
182 * @example
183 * A dependent query, only enabled once `postId` is set β€” use `isLoading`, not `isPending`, so the
184 * loading state doesn't show while the query is disabled:
185 * ```tsx
186 * import { useQuery } from '@tanstack/react-query'
187 *
188 * function Post({ postId }: { postId: number | undefined }) {
189 * const { data, isLoading, isError, error } = useQuery({
190 * queryKey: ['post', postId],
191 * queryFn: () => fetchPost(postId!),
192 * enabled: postId != null,
193 * })
194 *
195 * if (postId == null) return 'Select a post'
196 * if (isLoading) return 'Loading...'
197 * if (isError) return <span>Error: {error.message}</span>
198 *
199 * return <h1>{data?.title}</h1>
200 * }
201 * ```
202 *
203 * @example
204 * The same dependent query, type safe: `skipToken` disables the query without needing the
205 * non-null assertion above, since `queryFn` is only ever called when `postId` is defined.
206 * `refetch` doesn't work while `queryFn` is `skipToken` β€” use `enabled: false` instead if you
207 * need to trigger the query manually:
208 * ```tsx
209 * import { skipToken, useQuery } from '@tanstack/react-query'
210 *
211 * function Post({ postId }: { postId: number | undefined }) {
212 * const { data, isLoading, isError, error } = useQuery({
213 * queryKey: ['post', postId],
214 * queryFn: postId != null ? () => fetchPost(postId) : skipToken,
215 * })
216 *
217 * if (postId == null) return 'Select a post'
218 * if (isLoading) return 'Loading...'
219 * if (isError) return <span>Error: {error.message}</span>
220 *
221 * return <h1>{data?.title}</h1>
222 * }
223 * ```
224 *
225 * @example
226 * Seeding a detail query from an already-cached list, to skip the loading state:
227 * ```tsx
228 * import { useQuery, useQueryClient } from '@tanstack/react-query'
229 *
230 * function Post({ postId }: { postId: number }) {
231 * const queryClient = useQueryClient()
232 *
233 * const { data, isError, error } = useQuery({
234 * queryKey: ['post', postId],
235 * queryFn: () => fetchPost(postId),
236 * initialData: () =>
237 * queryClient
238 * .getQueryData<Array<Post>>(['posts'])
239 * ?.find((post) => post.id === postId),
240 * })
241 *
242 * if (isError) return <span>Error: {error.message}</span>
243 *
244 * return <h1>{data?.title}</h1>
245 * }
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)