Open History to see the last commit
1import { InfiniteQueryObserver, skipToken } from '@tanstack/query-core'
2import type {
3 DefaultError,
4 InfiniteData,
5 InfiniteQueryObserverSuccessResult,
6 QueryClient,
7 QueryKey,
8 QueryObserver,
9} from '@tanstack/query-core'
10β
11import { defaultThrowOnError } from './suspense'
12import type {
13 UseSuspenseInfiniteQueryOptions,
14 UseSuspenseInfiniteQueryResult,
15} from './types'
16import { useBaseQuery } from './useBaseQuery'
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 'preact/compat'
44 * import { useErrorBoundary } from 'preact/hooks'
45 * import {
46 * QueryErrorResetBoundary,
47 * useSuspenseInfiniteQuery,
48 * } from '@tanstack/preact-query'
49 * import type { ComponentChildren } from 'preact'
50 *
51 * function Projects() {
52 * // `data` is guaranteed to be defined here β no `isPending` check needed.
53 * const { data, fetchNextPage, hasNextPage, isFetching, isFetchingNextPage } =
54 * useSuspenseInfiniteQuery({
55 * queryKey: ['projects'],
56 * queryFn: ({ pageParam }) => fetchProjects(pageParam),
57 * initialPageParam: 0,
58 * getNextPageParam: (lastPage) => lastPage.nextId,
59 * })
60 *
61 * return (
62 * <div>
63 * <ul>
64 * {data.pages.map((page) =>
65 * page.projects.map((project) => <li key={project.id}>{project.name}</li>),
66 * )}
67 * </ul>
68 * <button
69 * onClick={() => fetchNextPage()}
70 * disabled={!hasNextPage || isFetching}
71 * >
72 * {isFetchingNextPage
73 * ? 'Loading more...'
74 * : hasNextPage
75 * ? 'Load More'
76 * : 'Nothing more to load'}
77 * </button>
78 * </div>
79 * )
80 * }
81 *
82 * function App() {
83 * return (
84 * <QueryErrorResetBoundary>
85 * {({ reset }) => (
86 * <ErrorBoundary
87 * onReset={reset}
88 * fallbackRender={({ resetErrorBoundary }) => (
89 * <div>
90 * There was an error!
91 * <button onClick={() => resetErrorBoundary()}>Try again</button>
92 * </div>
93 * )}
94 * >
95 * <Suspense fallback={<h1>Loading projects...</h1>}>
96 * <Projects />
97 * </Suspense>
98 * </ErrorBoundary>
99 * )}
100 * </QueryErrorResetBoundary>
101 * )
102 * }
103 *
104 * function ErrorBoundary({
105 * children,
106 * onReset,
107 * fallbackRender,
108 * }: {
109 * children: ComponentChildren
110 * onReset: () => void
111 * fallbackRender: (props: {
112 * error: Error
113 * resetErrorBoundary: () => void
114 * }) => ComponentChildren
115 * }) {
116 * const [error, resetErrorBoundary] = useErrorBoundary(() => onReset())
117 *
118 * if (error) return fallbackRender({ error, resetErrorBoundary })
119 *
120 * return children
121 * }
122 * ```
123 */
124export function useSuspenseInfiniteQuery<
125 TQueryFnData,
126 TError = DefaultError,
127 TData = InfiniteData<TQueryFnData>,
128 TQueryKey extends QueryKey = QueryKey,
129 TPageParam = unknown,
130>(
131 options: UseSuspenseInfiniteQueryOptions<
132 TQueryFnData,
133 TError,
134 TData,
135 TQueryKey,
136 TPageParam
137 >,
138 queryClient?: QueryClient,
139): UseSuspenseInfiniteQueryResult<TData, TError> {
140 if (process.env.NODE_ENV !== 'production') {
141 if ((options.queryFn as any) === skipToken) {
142 console.error('skipToken is not allowed for useSuspenseInfiniteQuery')
143 }
144 }
145β
146 return useBaseQuery(
147 {
148 ...options,
149 enabled: true,
150 suspense: true,
151 throwOnError: defaultThrowOnError,
152 placeholderData: undefined,
153 },
154 InfiniteQueryObserver as typeof QueryObserver,
155 queryClient,
156 ) as InfiniteQueryObserverSuccessResult<TData, TError>
157}