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