Skip to content
Source
Sign inSign up
TanStack/query
Open History to see the last commit

useSuspenseInfiniteQuery.ts

178 lines5.8 KB

1import { InfiniteQueryObserver, skipToken } from '@tanstack/query-core'
2import { defaultThrowOnError } from './suspense'
3import { useBaseQuery } from './useBaseQuery'
4import type {
5 DefaultError,
6 InfiniteData,
7 InfiniteQueryMode,
8 InfiniteQueryObserverSuccessResult,
9 QueryClient,
10 QueryKey,
11 QueryObserver,
12} from '@tanstack/query-core'
13​
14import type {
15 UseSuspenseInfiniteQueryOptions,
16 UseSuspenseInfiniteQueryResult,
17} from './types'
18​
19/**
20 * The options for `useSuspenseInfiniteQuery` are the same as for `useInfiniteQuery`, except for `throwOnError`,
21 * `enabled`, and `placeholderData`.
22 *
23 * Caveat: cancellation does not work.
24 * @param options - The {@link UseSuspenseInfiniteQueryOptions} to use β€” the same options as `useInfiniteQuery`, minus the ones listed above.
25 * @param queryClient - Use this to use a custom `QueryClient`. Otherwise, the one from the nearest context will
26 * be used.
27 * @returns The same object as `useInfiniteQuery`, except that `data` is guaranteed to be defined,
28 * `isPlaceholderData` is missing, and `status` is either `success` or `error` (with the derived flags set
29 * accordingly).
30 * @remarks Multiple suspenseful query calls in the same component suspend serially, causing a request
31 * waterfall β€” each one blocks rendering until it resolves, so the next doesn't even start fetching until
32 * then. There's no way to parallelize multiple infinite queries under Suspense. Also keep in mind that
33 * imperative fetch calls, such as `fetchNextPage`, may interfere with the default refetch behavior,
34 * resulting in outdated data. Make sure to call these functions only in response to user actions, or add
35 * conditions like `hasNextPage && !isFetching`.
36 * @see {@link useInfiniteQuery} for the non-Suspense version of this hook.
37 * @example
38 * The query error is thrown if a fetch fails and no cached data exists yet, so an error boundary is
39 * required around `<Suspense>`. A failed background refetch instead continues to render the cached data.
40 * Use {@link QueryErrorResetBoundary} to let the user retry after such an error:
41 * ```tsx
42 * import { Suspense } from 'preact/compat'
43 * import { useErrorBoundary } from 'preact/hooks'
44 * import {
45 * QueryErrorResetBoundary,
46 * useSuspenseInfiniteQuery,
47 * } from '@tanstack/preact-query'
48 * import type { ComponentChildren } from 'preact'
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 * function ErrorBoundary({
104 * children,
105 * onReset,
106 * fallbackRender,
107 * }: {
108 * children: ComponentChildren
109 * onReset: () => void
110 * fallbackRender: (props: {
111 * error: Error
112 * resetErrorBoundary: () => void
113 * }) => ComponentChildren
114 * }) {
115 * const [error, resetErrorBoundary] = useErrorBoundary(() => onReset())
116 *
117 * if (error) return fallbackRender({ error, resetErrorBoundary })
118 *
119 * return children
120 * }
121 * ```
122 */
123export function useSuspenseInfiniteQuery<
124 TQueryFnData,
125 TError = DefaultError,
126 TData = InfiniteData<TQueryFnData>,
127 TQueryKey extends QueryKey = QueryKey,
128 TPageParam = unknown,
129>(
130 options: UseSuspenseInfiniteQueryOptions<
131 TQueryFnData,
132 TError,
133 TData,
134 TQueryKey,
135 TPageParam,
136 undefined
137 >,
138 queryClient?: QueryClient,
139): UseSuspenseInfiniteQueryResult<TData, TError, TPageParam, undefined>
140export function useSuspenseInfiniteQuery<
141 TQueryFnData,
142 TError = DefaultError,
143 TData = InfiniteData<TQueryFnData>,
144 TQueryKey extends QueryKey = QueryKey,
145 TPageParam = unknown,
146>(
147 options: UseSuspenseInfiniteQueryOptions<
148 TQueryFnData,
149 TError,
150 TData,
151 TQueryKey,
152 TPageParam,
153 InfiniteQueryMode
154 >,
155 queryClient?: QueryClient,
156): UseSuspenseInfiniteQueryResult<TData, TError, TPageParam, InfiniteQueryMode>
157export function useSuspenseInfiniteQuery(
158 options: UseSuspenseInfiniteQueryOptions<any, any, any, any, any>,
159 queryClient?: QueryClient,
160): UseSuspenseInfiniteQueryResult<any, any, any, any> {
161 if (process.env.NODE_ENV !== 'production') {
162 if ((options.queryFn as any) === skipToken) {
163 console.error('skipToken is not allowed for useSuspenseInfiniteQuery')
164 }
165 }
166​
167 return useBaseQuery(
168 {
169 ...options,
170 enabled: true,
171 suspense: true,
172 throwOnError: defaultThrowOnError,
173 placeholderData: undefined,
174 },
175 InfiniteQueryObserver as typeof QueryObserver,
176 queryClient,
177 ) as InfiniteQueryObserverSuccessResult<any, any, any, any>