1- import React from ' react'
2- import axios from ' axios'
3- import { usePaginatedQuery } from ' react-query'
1+ import React from " react" ;
2+ import axios from " axios" ;
3+ import { usePaginatedQuery , queryCache } from " react-query" ;
44
55function Todos ( ) {
6- const [ page , setPage ] = React . useState ( 0 )
6+ const [ page , setPage ] = React . useState ( 0 ) ;
77
8- const fetchProjects = async ( key , page = 0 ) => {
9- const { data } = await axios . get ( ' /api/projects?page=' + page )
10- return data
11- }
8+ const fetchProjects = React . useCallback ( async ( key , page = 0 ) => {
9+ const { data } = await axios . get ( " /api/projects?page=" + page ) ;
10+ return data ;
11+ } , [ ] ) ;
1212
1313 const {
1414 status,
1515 resolvedData,
1616 latestData,
1717 error,
18- isFetching,
19- } = usePaginatedQuery ( [ 'projects' , page ] , fetchProjects )
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 ] ) ;
2027
2128 return (
2229 < div >
@@ -28,9 +35,9 @@ function Todos() {
2835 instantaneously while they are also refetched invisibly in the
2936 background.
3037 </ p >
31- { status === ' loading' ? (
38+ { status === " loading" ? (
3239 < div > Loading...</ div >
33- ) : status === ' error' ? (
40+ ) : status === " error" ? (
3441 < div > Error: { error . message } </ div >
3542 ) : (
3643 // `resolvedData` will either resolve to the latest page's data
@@ -47,7 +54,7 @@ function Todos() {
4754 disabled = { page === 0 }
4855 >
4956 Previous Page
50- </ button > { ' ' }
57+ </ button > { " " }
5158 < button
5259 onClick = { ( ) =>
5360 // Here, we use `latestData` so the Next Page
@@ -61,9 +68,9 @@ function Todos() {
6168 { // Since the last page's data potentially sticks around between page requests,
6269 // we can use `isFetching` to show a background loading
6370 // indicator since our `status === 'loading'` state won't be triggered
64- isFetching ? < span > Loading...</ span > : null } { ' ' }
71+ isFetching ? < span > Loading...</ span > : null } { " " }
6572 </ div >
66- )
73+ ) ;
6774}
6875
69- export default Todos
76+ export default Todos ;
0 commit comments