Open History to see the last commit
1---
2id: paginated-queries
3title: Paginated / Lagged Queries
4ref: docs/framework/react/guides/paginated-queries.md
5replace: { 'react-query': 'preact-query', 'React': 'Preact' }
6---
7β
8[//]: # 'Example2'
9β
10```tsx
11import { keepPreviousData, useQuery } from '@tanstack/preact-query'
12import { useState } from 'preact/hooks'
13β
14function Todos() {
15 const [page, setPage] = useState(0)
16β
17 const fetchProjects = (page = 0) =>
18 fetch('/api/projects?page=' + page).then((res) => res.json())
19β
20 const { isPending, isError, error, data, isFetching, isPlaceholderData } =
21 useQuery({
22 queryKey: ['projects', page],
23 queryFn: () => fetchProjects(page),
24 placeholderData: keepPreviousData,
25 })
26β
27 return (
28 <div>
29 {isPending ? (
30 <div>Loading...</div>
31 ) : isError ? (
32 <div>Error: {error.message}</div>
33 ) : (
34 <div>
35 {data.projects.map((project) => (
36 <p key={project.id}>{project.name}</p>
37 ))}
38 </div>
39 )}
40 <span>Current Page: {page + 1}</span>
41 <button
42 onClick={() => setPage((old) => Math.max(old - 1, 0))}
43 disabled={page === 0}
44 >
45 Previous Page
46 </button>
47 <button
48 onClick={() => {
49 if (!isPlaceholderData && data.hasMore) {
50 setPage((old) => old + 1)
51 }
52 }}
53 // Disable the Next Page button until we know a next page is available
54 disabled={isPlaceholderData || !data?.hasMore}
55 >
56 Next Page
57 </button>
58 {isFetching ? <span> Loading...</span> : null}
59 </div>
60 )
61}
62```
63β
64[//]: # 'Example2'