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