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

index.tsx

92 lines2.5 KB

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