Open History to see the last commit
1import { InfiniteQueryObserver, skipToken } from '@tanstack/query-core'
2import { defaultThrowOnError } from './suspense'
3import { useBaseQuery } from './useBaseQuery'
4import type {
5 DefaultError,
6 InfiniteData,
7 InfiniteQueryObserverSuccessResult,
8 QueryClient,
9 QueryKey,
10 QueryObserver,
11} from '@tanstack/query-core'
12β
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 'preact/compat'
42 * import { useErrorBoundary } from 'preact/hooks'
43 * import {
44 * QueryErrorResetBoundary,
45 * useSuspenseInfiniteQuery,
46 * } from '@tanstack/preact-query'
47 * import type { ComponentChildren } from 'preact'
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 * function ErrorBoundary({
103 * children,
104 * onReset,
105 * fallbackRender,
106 * }: {
107 * children: ComponentChildren
108 * onReset: () => void
109 * fallbackRender: (props: {
110 * error: Error
111 * resetErrorBoundary: () => void
112 * }) => ComponentChildren
113 * }) {
114 * const [error, resetErrorBoundary] = useErrorBoundary(() => onReset())
115 *
116 * if (error) return fallbackRender({ error, resetErrorBoundary })
117 *
118 * return children
119 * }
120 * ```
121 */
122export function useSuspenseInfiniteQuery<
123 TQueryFnData,
124 TError = DefaultError,
125 TData = InfiniteData<TQueryFnData>,
126 TQueryKey extends QueryKey = QueryKey,
127 TPageParam = unknown,
128>(
129 options: UseSuspenseInfiniteQueryOptions<
130 TQueryFnData,
131 TError,
132 TData,
133 TQueryKey,
134 TPageParam
135 >,
136 queryClient?: QueryClient,
137): UseSuspenseInfiniteQueryResult<TData, TError> {
138 if (process.env.NODE_ENV !== 'production') {
139 if ((options.queryFn as any) === skipToken) {
140 console.error('skipToken is not allowed for useSuspenseInfiniteQuery')
141 }
142 }
143β
144 return useBaseQuery(
145 {
146 ...options,
147 enabled: true,
148 suspense: true,
149 throwOnError: defaultThrowOnError,
150 placeholderData: undefined,
151 },
152 InfiniteQueryObserver as typeof QueryObserver,
153 queryClient,
154 ) as InfiniteQueryObserverSuccessResult<TData, TError>
155}