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