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

useInfiniteQuery.ts

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