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