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

useInfiniteQuery.ts

241 lines7.9 KB

1import { InfiniteQueryObserver } from '@tanstack/query-core'
2import { createMemo } from 'solid-js'
3import { useBaseQuery } from './useBaseQuery'
4import type {
5 DefaultError,
6 InfiniteData,
7 QueryKey,
8 QueryObserver,
9} from '@tanstack/query-core'
10import type { QueryClient } from './QueryClient'
11import type {
12 DefinedUseInfiniteQueryResult,
13 UseInfiniteQueryOptions,
14 UseInfiniteQueryResult,
15} from './types'
16import type { Accessor } from 'solid-js'
17import type {
18 DefinedInitialDataInfiniteOptions,
19 UndefinedInitialDataInfiniteOptions,
20} from './infiniteQueryOptions'
21​
22/**
23 * The options for `useInfiniteQuery` are identical to `useQuery`, with the
24 * addition of `initialPageParam`, `getNextPageParam`, `getPreviousPageParam`,
25 * and `maxPages`.
26 *
27 * This overload is selected when `initialData` is set.
28 *
29 * @remarks
30 * Keep in mind that imperative fetch calls, such as `fetchNextPage`, may
31 * interfere with the default refetch behavior, resulting in outdated data.
32 * Make sure to call these functions only in response to user actions, or add
33 * conditions like `hasNextPage && !isFetching`.
34 * @example
35 * ```tsx
36 * import { For } from 'solid-js'
37 * import { useInfiniteQuery } from '@tanstack/solid-query'
38 *
39 * function Projects() {
40 * // `projectsQuery.data` is never `undefined`, thanks to `initialData` β€” even if a refetch fails, so the
41 * // list stays visible alongside the error.
42 * const projectsQuery = useInfiniteQuery(() => ({
43 * queryKey: ['projects'],
44 * queryFn: ({ pageParam }) => fetchProjects(pageParam),
45 * initialPageParam: 0,
46 * getNextPageParam: (lastPage) => lastPage.nextId,
47 * initialData: { pages: [], pageParams: [] },
48 * }))
49 *
50 * return (
51 * <div>
52 * {projectsQuery.isError ? (
53 * <span>Error: {projectsQuery.error.message}</span>
54 * ) : null}
55 * <ul>
56 * <For each={projectsQuery.data.pages}>
57 * {(page) => (
58 * <For each={page.projects}>{(p) => <li>{p.name}</li>}</For>
59 * )}
60 * </For>
61 * </ul>
62 * </div>
63 * )
64 * }
65 * ```
66 *
67 * @param options - An accessor returning the
68 * {@link DefinedInitialDataInfiniteOptions} to use β€” everything you can pass
69 * to `useInfiniteQuery`, with `initialData` set.
70 * @param queryClient - An accessor for a custom `QueryClient`. Otherwise, the
71 * one from the nearest context will be used.
72 * @returns The same properties as `useQuery`, with the addition of
73 * `fetchNextPage`, `fetchPreviousPage`, `hasNextPage`, `hasPreviousPage`,
74 * `isFetchingNextPage`, and `isFetchingPreviousPage`. `data.pages` and
75 * `data.pageParams` are also added, as long as a `select` doesn't change
76 * `TData` away from its default `InfiniteData<TQueryFnData>` shape.
77 * @see {@link infiniteQueryOptions} to share these options between `useInfiniteQuery` and imperative APIs like `queryClient.infiniteQuery`.
78 */
79export function useInfiniteQuery<
80 TQueryFnData,
81 TError = DefaultError,
82 TData = InfiniteData<TQueryFnData>,
83 TQueryKey extends QueryKey = QueryKey,
84 TPageParam = unknown,
85>(
86 options: DefinedInitialDataInfiniteOptions<
87 TQueryFnData,
88 TError,
89 TData,
90 TQueryKey,
91 TPageParam
92 >,
93 queryClient?: Accessor<QueryClient>,
94): DefinedUseInfiniteQueryResult<TData, TError>
95​
96/**
97 * The options for `useInfiniteQuery` are identical to `useQuery`, with the
98 * addition of `initialPageParam`, `getNextPageParam`, `getPreviousPageParam`,
99 * and `maxPages`.
100 *
101 * @remarks
102 * Keep in mind that imperative fetch calls, such as `fetchNextPage`, may
103 * interfere with the default refetch behavior, resulting in outdated data.
104 * Make sure to call these functions only in response to user actions, or add
105 * conditions like `hasNextPage && !isFetching`.
106 * @example
107 * Fetching the next page from a "Load More" button click:
108 * ```tsx
109 * import { For, Match, Switch } from 'solid-js'
110 * import { useInfiniteQuery } from '@tanstack/solid-query'
111 *
112 * function Projects() {
113 * const projectsQuery = useInfiniteQuery(() => ({
114 * queryKey: ['projects'],
115 * queryFn: ({ pageParam }) => fetchProjects(pageParam),
116 * initialPageParam: 0,
117 * getNextPageParam: (lastPage) => lastPage.nextId,
118 * }))
119 *
120 * return (
121 * <Switch>
122 * <Match when={projectsQuery.isPending}>Loading...</Match>
123 * <Match when={projectsQuery.isError}>Error: {projectsQuery.error.message}</Match>
124 * <Match when={projectsQuery.isSuccess}>
125 * <ul>
126 * <For each={projectsQuery.data.pages}>
127 * {(page) => <For each={page.projects}>{(p) => <li>{p.name}</li>}</For>}
128 * </For>
129 * </ul>
130 * <button
131 * onClick={() => projectsQuery.fetchNextPage()}
132 * disabled={!projectsQuery.hasNextPage || projectsQuery.isFetching}
133 * >
134 * {projectsQuery.isFetchingNextPage
135 * ? 'Loading more...'
136 * : projectsQuery.hasNextPage
137 * ? 'Load More'
138 * : 'Nothing more to load'}
139 * </button>
140 * </Match>
141 * </Switch>
142 * )
143 * }
144 * ```
145 *
146 * @example
147 * Fetching the next page automatically as the user scrolls, using an `IntersectionObserver` on a
148 * sentinel element after the list:
149 * ```tsx
150 * import { For, Match, Switch, createEffect, onCleanup } from 'solid-js'
151 * import { useInfiniteQuery } from '@tanstack/solid-query'
152 *
153 * function Projects() {
154 * const projectsQuery = useInfiniteQuery(() => ({
155 * queryKey: ['projects'],
156 * queryFn: ({ pageParam }) => fetchProjects(pageParam),
157 * initialPageParam: 0,
158 * getNextPageParam: (lastPage) => lastPage.nextId,
159 * }))
160 *
161 * let sentinelRef: HTMLDivElement | undefined
162 *
163 * createEffect(() => {
164 * if (sentinelRef == null || !projectsQuery.hasNextPage || projectsQuery.isFetching) return
165 *
166 * const observer = new IntersectionObserver(([entry]) => {
167 * if (entry?.isIntersecting) projectsQuery.fetchNextPage()
168 * })
169 * observer.observe(sentinelRef)
170 *
171 * onCleanup(() => observer.disconnect())
172 * })
173 *
174 * return (
175 * <Switch>
176 * <Match when={projectsQuery.isPending}>Loading...</Match>
177 * <Match when={projectsQuery.isError}>Error: {projectsQuery.error.message}</Match>
178 * <Match when={projectsQuery.isSuccess}>
179 * <ul>
180 * <For each={projectsQuery.data.pages}>
181 * {(page) => <For each={page.projects}>{(p) => <li>{p.name}</li>}</For>}
182 * </For>
183 * </ul>
184 * <div ref={sentinelRef}>{projectsQuery.isFetchingNextPage ? 'Loading more...' : null}</div>
185 * </Match>
186 * </Switch>
187 * )
188 * }
189 * ```
190 *
191 * @param options - An accessor returning the
192 * {@link UndefinedInitialDataInfiniteOptions} to use β€” everything you can
193 * pass to `useInfiniteQuery`.
194 * @param queryClient - An accessor for a custom `QueryClient`. Otherwise, the
195 * one from the nearest context will be used.
196 * @returns The same properties as `useQuery`, with the addition of
197 * `fetchNextPage`, `fetchPreviousPage`, `hasNextPage`, `hasPreviousPage`,
198 * `isFetchingNextPage`, and `isFetchingPreviousPage`. `data.pages` and
199 * `data.pageParams` are also added, as long as a `select` doesn't change
200 * `TData` away from its default `InfiniteData<TQueryFnData>` shape.
201 * @see {@link infiniteQueryOptions} to share these options between `useInfiniteQuery` and imperative APIs like `queryClient.infiniteQuery`.
202 */
203export function useInfiniteQuery<
204 TQueryFnData,
205 TError = DefaultError,
206 TData = InfiniteData<TQueryFnData>,
207 TQueryKey extends QueryKey = QueryKey,
208 TPageParam = unknown,
209>(
210 options: UndefinedInitialDataInfiniteOptions<
211 TQueryFnData,
212 TError,
213 TData,
214 TQueryKey,
215 TPageParam
216 >,
217 queryClient?: Accessor<QueryClient>,
218): UseInfiniteQueryResult<TData, TError>
219​
220export function useInfiniteQuery<
221 TQueryFnData,
222 TError = DefaultError,
223 TData = InfiniteData<TQueryFnData>,
224 TQueryKey extends QueryKey = QueryKey,
225 TPageParam = unknown,
226>(
227 options: UseInfiniteQueryOptions<
228 TQueryFnData,
229 TError,
230 TData,
231 TQueryKey,
232 TPageParam
233 >,
234 queryClient?: Accessor<QueryClient>,
235): UseInfiniteQueryResult<TData, TError> {
236 return useBaseQuery(
237 createMemo(() => options()),
238 InfiniteQueryObserver as typeof QueryObserver,
239 queryClient,
240 ) as UseInfiniteQueryResult<TData, TError>