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

useSuspenseInfiniteQuery.ts

154 lines5.1 KB

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