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