Open History to see the last commit
1'use client'
2import { InfiniteQueryObserver, skipToken } from '@tanstack/query-core'
3import { useBaseQuery } from './useBaseQuery'
4import { defaultThrowOnError } from './suspense'
5import type {
6 DefaultError,
7 InfiniteData,
8 InfiniteQueryObserverSuccessResult,
9 QueryClient,
10 QueryKey,
11 QueryObserver,
12} from '@tanstack/query-core'
13import type {
14 UseSuspenseInfiniteQueryOptions,
15 UseSuspenseInfiniteQueryResult,
16} from './types'
17β
18/**
19 * The options for `useSuspenseInfiniteQuery` are the same as for
20 * `useInfiniteQuery`, except for `throwOnError`, `enabled`, and
21 * `placeholderData`.
22 *
23 * Caveat: cancellation does not work.
24 *
25 * @remarks
26 * Multiple suspenseful query calls in the same component suspend serially,
27 * causing a request waterfall β each one blocks rendering until it resolves,
28 * so the next doesn't even start fetching until then. There's no way to
29 * parallelize multiple infinite queries under Suspense. Also keep in mind
30 * that imperative fetch calls, such as `fetchNextPage`, may interfere with
31 * the default refetch behavior, resulting in outdated data. Make sure to call
32 * these functions only in response to user actions, or add conditions like
33 * `hasNextPage && !isFetching`.
34 * @example
35 * The query error is thrown if a fetch fails and no cached data exists yet, so an error boundary is
36 * required around `<Suspense>`. A failed background refetch instead continues to render the cached data.
37 * Use {@link QueryErrorResetBoundary} to let the user retry after such an error:
38 * ```tsx
39 * import { Suspense } from 'react'
40 * import { ErrorBoundary } from 'react-error-boundary'
41 * import {
42 * QueryErrorResetBoundary,
43 * useSuspenseInfiniteQuery,
44 * } from '@tanstack/react-query'
45 *
46 * function Projects() {
47 * // `data` is guaranteed to be defined here β no `isPending` check needed.
48 * const { data, fetchNextPage, hasNextPage, isFetching, isFetchingNextPage } =
49 * useSuspenseInfiniteQuery({
50 * queryKey: ['projects'],
51 * queryFn: ({ pageParam }) => fetchProjects(pageParam),
52 * initialPageParam: 0,
53 * getNextPageParam: (lastPage) => lastPage.nextId,
54 * })
55 *
56 * return (
57 * <div>
58 * <ul>
59 * {data.pages.map((page) =>
60 * page.projects.map((project) => <li key={project.id}>{project.name}</li>),
61 * )}
62 * </ul>
63 * <button
64 * onClick={() => fetchNextPage()}
65 * disabled={!hasNextPage || isFetching}
66 * >
67 * {isFetchingNextPage
68 * ? 'Loading more...'
69 * : hasNextPage
70 * ? 'Load More'
71 * : 'Nothing more to load'}
72 * </button>
73 * </div>
74 * )
75 * }
76 *
77 * function App() {
78 * return (
79 * <QueryErrorResetBoundary>
80 * {({ reset }) => (
81 * <ErrorBoundary
82 * onReset={reset}
83 * fallbackRender={({ resetErrorBoundary }) => (
84 * <div>
85 * There was an error!
86 * <button onClick={() => resetErrorBoundary()}>Try again</button>
87 * </div>
88 * )}
89 * >
90 * <Suspense fallback={<h1>Loading projects...</h1>}>
91 * <Projects />
92 * </Suspense>
93 * </ErrorBoundary>
94 * )}
95 * </QueryErrorResetBoundary>
96 * )
97 * }
98 * ```
99 *
100 * @param options - The {@link UseSuspenseInfiniteQueryOptions} to use β the
101 * same options as `useInfiniteQuery`, minus the ones listed above.
102 * @param queryClient - Use this to use a custom `QueryClient`. Otherwise, the
103 * one from the nearest context will be used.
104 * @returns The same object as `useInfiniteQuery`, except that `data` is
105 * guaranteed to be defined, `isPlaceholderData` is missing, and `status` is
106 * either `success` or `error` (with the derived flags set accordingly).
107 * @see {@link useInfiniteQuery} for the non-Suspense version of this hook.
108 */
109export function useSuspenseInfiniteQuery<
110 TQueryFnData,
111 TError = DefaultError,
112 TData = InfiniteData<TQueryFnData>,
113 TQueryKey extends QueryKey = QueryKey,
114 TPageParam = unknown,
115>(
116 options: UseSuspenseInfiniteQueryOptions<
117 TQueryFnData,
118 TError,
119 TData,
120 TQueryKey,
121 TPageParam
122 >,
123 queryClient?: QueryClient,
124): UseSuspenseInfiniteQueryResult<TData, TError> {
125 if (process.env.NODE_ENV !== 'production') {
126 if ((options.queryFn as any) === skipToken) {
127 console.error('skipToken is not allowed for useSuspenseInfiniteQuery')
128 }
129 }
130β
131 return useBaseQuery(
132 {
133 ...options,
134 enabled: true,
135 suspense: true,
136 throwOnError: defaultThrowOnError,
137 placeholderData: undefined,
138 },
139 InfiniteQueryObserver as typeof QueryObserver,
140 queryClient,
141 ) as InfiniteQueryObserverSuccessResult<TData, TError>
142}