Skip to content
Source
Sign inSign up
TanStack/query
Open History to see the last commit

index.tsx

102 lines2.9 KB

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