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

App.tsx

74 lines2.4 KB

1import { useEffect, useState } from 'preact/hooks'
2import {
3 keepPreviousData,
4 noop,
5 useQuery,
6 useQueryClient,
7} from '@tanstack/preact-query'
8import { PreactQueryDevtools } from '@tanstack/preact-query-devtools'
9import { projectsQueries } from './services/projects/queries'
10​
11export default function App() {
12 const queryClient = useQueryClient()
13 const [page, setPage] = useState(0)
14​
15 const { status, data, error, isFetching, isPlaceholderData } = useQuery({
16 ...projectsQueries.list(page),
17 placeholderData: keepPreviousData,
18 })
19​
20 // Prefetch the next page!
21 useEffect(() => {
22 if (!isPlaceholderData && data?.hasMore) {
23 queryClient.query(projectsQueries.list(page + 1)).catch(noop)
24 }
25 }, [data, isPlaceholderData, page, queryClient])
26​
27 return (
28 <div>
29 <p>
30 In this example, each page of data remains visible as the next page is
31 fetched. The buttons and capability to proceed to the next page are also
32 suppressed until the next page cursor is known. Each page is cached as a
33 normal query too, so when going to previous pages, you'll see them
34 instantaneously while they are also refetched invisibly in the
35 background.
36 </p>
37 {status === 'pending' ? (
38 <div>Loading...</div>
39 ) : status === 'error' ? (
40 <div>Error: {error.message}</div>
41 ) : (
42 // `data` will either resolve to the latest page's data
43 // or if fetching a new page, the last successful page's data
44 <div>
45 {data.projects.map((project) => (
46 <p key={project.id}>{project.name}</p>
47 ))}
48 </div>
49 )}
50 <div>Current Page: {page + 1}</div>
51 <button
52 onClick={() => setPage((old) => Math.max(old - 1, 0))}
53 disabled={page === 0}
54 >
55 Previous Page
56 </button>{' '}
57 <button
58 onClick={() => {
59 setPage((old) => (data?.hasMore ? old + 1 : old))
60 }}
61 disabled={isPlaceholderData || !data?.hasMore}
62 >
63 Next Page
64 </button>
65 {
66 // Since the last page's data potentially sticks around between page requests,
67 // we can use `isFetching` to show a background loading
68 // indicator since our `status === 'pending'` state won't be triggered
69 isFetching ? <span> Loading...</span> : null
70 }{' '}
71 <PreactQueryDevtools initialIsOpen />
72 </div>
73 )