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