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

useSuspenseQuery.ts

83 lines2.7 KB

1import { QueryObserver, skipToken } from '@tanstack/query-core'
2import type { DefaultError, QueryClient, QueryKey } from '@tanstack/query-core'
3​
4import { defaultThrowOnError } from './suspense'
5import type { UseSuspenseQueryOptions, UseSuspenseQueryResult } from './types'
6import { useBaseQuery } from './useBaseQuery'
7​
8/**
9 * The options for `useSuspenseQuery` are the same as for `useQuery`, except for `throwOnError`, `enabled`, and
10 * `placeholderData`.
11 *
12 * Caveat: cancellation does not work.
13 *
14 * @remarks Multiple `useSuspenseQuery` calls in the same component suspend serially, causing a request
15 * waterfall β€” each one blocks rendering until it resolves, so the next doesn't even start fetching until then.
16 * Use {@link useSuspenseQueries} instead when you have more than one suspenseful query in a component, so they
17 * fetch in parallel.
18 * @param options - The {@link UseSuspenseQueryOptions} to use β€” the same options as `useQuery`, minus the ones listed above.
19 * @param queryClient - Use this to use a custom `QueryClient`. Otherwise, the one from the nearest context will
20 * be used.
21 * @returns The same object as `useQuery`, except that `data` is guaranteed to be defined, `isPlaceholderData`
22 * is missing, and `status` is either `success` or `error` (with the derived flags set accordingly).
23 *
24 * @example
25 * ```tsx
26 * import { Suspense } from 'preact/compat'
27 * import { useSuspenseQuery } from '@tanstack/preact-query'
28 *
29 * function Posts() {
30 * // `data` is guaranteed to be defined here β€” no `isPending` check needed.
31 * const { data, isFetching } = useSuspenseQuery({
32 * queryKey: ['posts'],
33 * queryFn: fetchPosts,
34 * })
35 *
36 * return (
37 * <div>
38 * <h1>Posts {isFetching ? '(refreshing...)' : null}</h1>
39 * <ul>
40 * {data.map((post) => (
41 * <li key={post.id}>{post.title}</li>
42 * ))}
43 * </ul>
44 * </div>
45 * )
46 * }
47 *
48 * function App() {
49 * return (
50 * <Suspense fallback={<h1>Loading posts...</h1>}>
51 * <Posts />
52 * </Suspense>
53 * )
54 * }
55 * ```
56 */
57export function useSuspenseQuery<
58 TQueryFnData = unknown,
59 TError = DefaultError,
60 TData = TQueryFnData,
61 TQueryKey extends QueryKey = QueryKey,
62>(
63 options: UseSuspenseQueryOptions<TQueryFnData, TError, TData, TQueryKey>,
64 queryClient?: QueryClient,
65): UseSuspenseQueryResult<TData, TError> {
66 if (process.env.NODE_ENV !== 'production') {
67 if ((options.queryFn as any) === skipToken) {
68 console.error('skipToken is not allowed for useSuspenseQuery')
69 }
70 }
71​
72 return useBaseQuery(
73 {
74 ...options,
75 enabled: true,
76 suspense: true,
77 throwOnError: defaultThrowOnError,
78 placeholderData: undefined,
79 },
80 QueryObserver,
81 queryClient,
82 ) as UseSuspenseQueryResult<TData, TError>