66 lines
1.4 KiB
Markdown
66 lines
1.4 KiB
Markdown
---
|
|
id: infinite-queries
|
|
title: Infinite Queries
|
|
ref: docs/framework/react/guides/infinite-queries.md
|
|
replace: { 'react-query': 'preact-query', 'React': 'Preact' }
|
|
---
|
|
|
|
[//]: # 'Example'
|
|
|
|
```tsx
|
|
import { useInfiniteQuery } from '@tanstack/preact-query'
|
|
|
|
function Projects() {
|
|
const fetchProjects = async ({ pageParam }) => {
|
|
const res = await fetch('/api/projects?cursor=' + pageParam)
|
|
return res.json()
|
|
}
|
|
|
|
const {
|
|
data,
|
|
error,
|
|
fetchNextPage,
|
|
hasNextPage,
|
|
isFetching,
|
|
isFetchingNextPage,
|
|
status,
|
|
} = useInfiniteQuery({
|
|
queryKey: ['projects'],
|
|
queryFn: fetchProjects,
|
|
initialPageParam: 0,
|
|
getNextPageParam: (lastPage, pages) => lastPage.nextCursor,
|
|
})
|
|
|
|
return status === 'pending' ? (
|
|
<p>Loading...</p>
|
|
) : status === 'error' ? (
|
|
<p>Error: {error.message}</p>
|
|
) : (
|
|
<>
|
|
{data.pages.map((group, i) => (
|
|
<div key={i}>
|
|
{group.data.map((project) => (
|
|
<p key={project.id}>{project.name}</p>
|
|
))}
|
|
</div>
|
|
))}
|
|
<div>
|
|
<button
|
|
onClick={() => fetchNextPage()}
|
|
disabled={!hasNextPage || isFetching}
|
|
>
|
|
{isFetchingNextPage
|
|
? 'Loading more...'
|
|
: hasNextPage
|
|
? 'Load More'
|
|
: 'Nothing more to load'}
|
|
</button>
|
|
</div>
|
|
<div>{isFetching && !isFetchingNextPage ? 'Fetching...' : null}</div>
|
|
</>
|
|
)
|
|
}
|
|
```
|
|
|
|
[//]: # 'Example'
|