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