Open History to see the last commit
1import React from 'react'
2import {
3 keepPreviousData,
4 noop,
5 useQuery,
6 useQueryClient,
7} from '@tanstack/react-query'
8import { ReactQueryDevtools } from '@tanstack/react-query-devtools'
9β
10const fetchProjects = async (
11 page = 0,
12): Promise<{
13 projects: Array<{ name: string; id: number }>
14 hasMore: boolean
15}> => {
16 const response = await fetch(`/api/projects?page=${page}`)
17 return await response.json()
18}
19β
20export default function Example() {
21 const queryClient = useQueryClient()
22 const [page, setPage] = React.useState(0)
23β
24 const { status, data, error, isFetching, isPlaceholderData } = useQuery({
25 queryKey: ['projects', page],
26 queryFn: () => fetchProjects(page),
27 placeholderData: keepPreviousData,
28 staleTime: 5000,
29 })
30β
31 // Prefetch the next page!
32 React.useEffect(() => {
33 if (!isPlaceholderData && data?.hasMore) {
34 queryClient
35 .query({
36 queryKey: ['projects', page + 1],
37 queryFn: () => fetchProjects(page + 1),
38 })
39 .catch(noop)
40 }
41 }, [data, isPlaceholderData, page, queryClient])
42β
43 return (
44 <div>
45 <p>
46 In this example, each page of data remains visible as the next page is
47 fetched. The buttons and capability to proceed to the next page are also
48 suppressed until the next page cursor is known. Each page is cached as a
49 normal query too, so when going to previous pages, you'll see them
50 instantaneously while they are also refetched invisibly in the
51 background.
52 </p>
53 {status === 'pending' ? (
54 <div>Loading...</div>
55 ) : status === 'error' ? (
56 <div>Error: {error.message}</div>
57 ) : (
58 // `data` will either resolve to the latest page's data
59 // or if fetching a new page, the last successful page's data
60 <div>
61 {data.projects.map((project) => (
62 <p key={project.id}>{project.name}</p>
63 ))}
64 </div>
65 )}
66 <div>Current Page: {page + 1}</div>
67 <button
68 onClick={() => setPage((old) => Math.max(old - 1, 0))}
69 disabled={page === 0}
70 >
71 Previous Page
72 </button>{' '}
73 <button
74 onClick={() => {
75 setPage((old) => (data?.hasMore ? old + 1 : old))
76 }}
77 disabled={isPlaceholderData || !data?.hasMore}
78 >
79 Next Page
80 </button>
81 {
82 // Since the last page's data potentially sticks around between page requests,
83 // we can use `isFetching` to show a background loading
84 // indicator since our `status === 'pending'` state won't be triggered
85 isFetching ? <span> Loading...</span> : null
86 }{' '}
87 <ReactQueryDevtools initialIsOpen />
88 </div>
89 )
90}