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

infinite-queries.md

89 lines2.7 KB

1---
2id: infinite-queries
3title: Infinite Queries
4---
5​
6Infinite queries are for lists that load more data into one cache entry. Use [`createInfiniteQueryController`](../reference/functions/createInfiniteQueryController.md).
7​
8An infinite query result contains:
9​
10- `data.pages`: fetched pages
11- `data.pageParams`: page parameters used for those pages
12- `fetchNextPage` and `fetchPreviousPage`
13- `hasNextPage` and `hasPreviousPage`
14- `isFetchingNextPage` and `isFetchingPreviousPage`
15​
16## Load More Example
17​
18```ts
19import { LitElement, html } from 'lit'
20import { createInfiniteQueryController } from '@tanstack/lit-query'
21​
22class ProjectsList extends LitElement {
23 private readonly projects = createInfiniteQueryController(this, {
24 queryKey: ['projects'],
25 queryFn: ({ pageParam }) => fetchProjectsPage(pageParam),
26 initialPageParam: 1,
27 getNextPageParam: (lastPage) =>
28 lastPage.hasMore ? lastPage.page + 1 : undefined,
29 })
30​
31 render() {
32 const query = this.projects()
33​
34 if (query.isPending) return html`Loading...`
35 if (query.isError) return html`Error: ${query.error.message}`
36​
37 return html`
38 ${query.data.pages.map(
39 (page) => html`
40 ${page.projects.map((project) => html`<p>${project.name}</p>`)}
41 `,
42 )}
43​
44 <button
45 ?disabled=${!query.hasNextPage || query.isFetching}
46 @click=${() => this.projects.fetchNextPage()}
47 >
48 ${
49 query.isFetchingNextPage
50 ? 'Loading more...'
51 : query.hasNextPage
52 ? 'Load More'
53 : 'Nothing more to load'
54 }
55 </button>
56 `
57 }
59```
60​
61## Page Parameters
62​
63`initialPageParam` is required. `getNextPageParam` decides whether another page exists and what value should be passed as `pageParam` to the next query function call.
64​
65```ts
66createInfiniteQueryController(this, {
67 queryKey: ['projects'],
68 queryFn: ({ pageParam }) => fetchProjectsPage(pageParam),
69 initialPageParam: 1,
70 getNextPageParam: (lastPage) =>
71 lastPage.hasMore ? lastPage.page + 1 : undefined,
72})
73```
74​
75Returning `undefined` or `null` means there is no next page.
76​
77## Avoid Overlapping Fetches
78​
79There is one ongoing fetch for an infinite query cache entry. If you call `fetchNextPage` while a background refetch is running, you can overwrite data. Disable the button or check `!query.isFetching` before loading more:
80​
81```ts
82if (query.hasNextPage && !query.isFetching) {
83 this.projects.fetchNextPage()
85```
86​
87## Paginated Alternative
88​
89If your UI shows one page at a time, a normal query with a page in the key can be a better fit. The [Pagination example](../examples/pagination) uses `createQueryController`, `placeholderData: keepPreviousData`, prefetching, and mutations to demonstrate that pattern.