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