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