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

useQuery.ts

305 lines9.7 KB

1import { QueryObserver } from '@tanstack/query-core'
2import type { DefaultError, QueryClient, QueryKey } from '@tanstack/query-core'
3​
4import type {
5 DefinedInitialDataOptions,
6 UndefinedInitialDataOptions,
7} from './queryOptions'
8import type {
9 DefinedUseQueryResult,
10 UseQueryOptions,
11 UseQueryResult,
12} from './types'
13import { useBaseQuery } from './useBaseQuery'
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/preact-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 and no query attempt
66 * has finished yet, `error` if the query attempt resulted in an error, or `success` if the query has data to
67 * display. `isPending`/`isSuccess`/`isError` are derived booleans for convenience.
68 *
69 * @example
70 * ```tsx
71 * import { useQuery } from '@tanstack/preact-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/preact-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 and no query attempt
133 * has finished yet, `error` if the query attempt resulted in an error, or `success` if the query has data to
134 * display. `isPending`/`isSuccess`/`isError` are derived booleans for convenience.
135 *
136 * @example
137 * ```tsx
138 * import { useQuery } from '@tanstack/preact-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 * A dependent query, only enabled once `postId` is set β€” use `isLoading`, not `isPending`, so the
164 * loading state doesn't show while the query is disabled:
165 * ```tsx
166 * import { useQuery } from '@tanstack/preact-query'
167 *
168 * function Post({ postId }: { postId: number | undefined }) {
169 * const { data, isLoading, isError, error } = useQuery({
170 * queryKey: ['post', postId],
171 * queryFn: () => fetchPost(postId!),
172 * enabled: postId != null,
173 * })
174 *
175 * if (postId == null) return 'Select a post'
176 * if (isLoading) return 'Loading...'
177 * if (isError) return <span>Error: {error.message}</span>
178 *
179 * return <h1>{data?.title}</h1>
180 * }
181 * ```
182 *
183 * @example
184 * The same dependent query, type safe: `skipToken` disables the query without needing the
185 * non-null assertion above, since `queryFn` is only ever called when `postId` is defined.
186 * `refetch` doesn't work while `queryFn` is `skipToken` β€” use `enabled: false` instead if you
187 * need to trigger the query manually:
188 * ```tsx
189 * import { skipToken, useQuery } from '@tanstack/preact-query'
190 *
191 * function Post({ postId }: { postId: number | undefined }) {
192 * const { data, isLoading, isError, error } = useQuery({
193 * queryKey: ['post', postId],
194 * queryFn: postId != null ? () => fetchPost(postId) : skipToken,
195 * })
196 *
197 * if (postId == null) return 'Select a post'
198 * if (isLoading) return 'Loading...'
199 * if (isError) return <span>Error: {error.message}</span>
200 *
201 * return <h1>{data?.title}</h1>
202 * }
203 * ```
204 *
205 * @example
206 * Seeding a detail query from an already-cached list, to skip the loading state:
207 * ```tsx
208 * import { useQuery, useQueryClient } from '@tanstack/preact-query'
209 *
210 * function Post({ postId }: { postId: number }) {
211 * const queryClient = useQueryClient()
212 *
213 * const { data, isError, error } = useQuery({
214 * queryKey: ['post', postId],
215 * queryFn: () => fetchPost(postId),
216 * initialData: () =>
217 * queryClient
218 * .getQueryData<Array<Post>>(['posts'])
219 * ?.find((post) => post.id === postId),
220 * })
221 *
222 * if (isError) return <span>Error: {error.message}</span>
223 *
224 * return <h1>{data?.title}</h1>
225 * }
226 * ```
227 *
228 * @example
229 * Paginated data, keeping the previous page's data visible while the next page loads:
230 * ```tsx
231 * import { keepPreviousData, useQuery } from '@tanstack/preact-query'
232 * import { useState } from 'preact/hooks'
233 *
234 * function Posts() {
235 * const [page, setPage] = useState(0)
236 *
237 * const { data, isPlaceholderData, isError, error } = useQuery({
238 * queryKey: ['posts', page],
239 * queryFn: () => fetchPosts(page),
240 * placeholderData: keepPreviousData,
241 * })
242 *
243 * if (isError) return <span>Error: {error.message}</span>
244 *
245 * return (
246 * <div>
247 * <ul>
248 * {data?.map((post) => <li key={post.id}>{post.title}</li>)}
249 * </ul>
250 * <button
251 * disabled={isPlaceholderData}
252 * onClick={() => setPage((old) => old + 1)}
253 * >
254 * Next Page
255 * </button>
256 * </div>
257 * )
258 * }
259 * ```
260 *
261 * @example
262 * Warming the cache on hover, so `<Post>` has data as soon as it's clicked. Requires a
263 * {@link queryOptions} factory, so the hook and the imperative call share the same cache entry:
264 * ```tsx
265 * import { noop, queryOptions, useQuery, useQueryClient } from '@tanstack/preact-query'
266 *
267 * const postOptions = (id: string) =>
268 * queryOptions({
269 * queryKey: ['post', id],
270 * queryFn: () => fetchPost(id),
271 * })
272 *
273 * function Post({ id }: { id: string }) {
274 * const { data, isError, error } = useQuery(postOptions(id))
275 * if (isError) return <span>Error: {error.message}</span>
276 * return <h1>{data?.title}</h1>
277 * }
278 *
279 * function PostLink({ id, title }: { id: string; title: string }) {
280 * const queryClient = useQueryClient()
281 *
282 * return (
283 * <a
284 * href={`/posts/${id}`}
285 * onMouseEnter={() => queryClient.query(postOptions(id)).catch(noop)}
286 * >
287 * {title}
288 * </a>
289 * )
290 * }
291 * ```
292 */
293export function useQuery<
294 TQueryFnData = unknown,
295 TError = DefaultError,
296 TData = TQueryFnData,
297 TQueryKey extends QueryKey = QueryKey,
298>(
299 options: UseQueryOptions<TQueryFnData, TError, TData, TQueryKey>,
300 queryClient?: QueryClient,
301): UseQueryResult<TData, TError>
302​
303export function useQuery(options: UseQueryOptions, queryClient?: QueryClient) {
304 return useBaseQuery(options, QueryObserver, queryClient)