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

index.js

94 lines2.7 KB

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