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

useSuspenseQuery.ts

99 lines3.6 KB

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