Open History to see the last commit
1---
2id: paginated-queries
3title: Paginated / Lagged Queries
4ref: docs/framework/react/guides/paginated-queries.md
5replace: { 'hook': 'primitive' }
6---
7β
8[//]: # 'Example'
9β
10```tsx
11const projectsQuery = useQuery(() => ({
12 queryKey: ['projects', page()],
13 queryFn: () => fetchProjects(page()),
14}))
15```
16β
17[//]: # 'Example'
18[//]: # 'Example2'
19β
20```tsx
21import { createSignal, Switch, Match, Show, For } from 'solid-js'
22import { keepPreviousData, useQuery } from '@tanstack/solid-query'
23β
24function Todos() {
25 const [page, setPage] = createSignal(0)
26β
27 const fetchProjects = (page = 0) =>
28 fetch('/api/projects?page=' + page).then((res) => res.json())
29β
30 const projectsQuery = useQuery(() => ({
31 queryKey: ['projects', page()],
32 queryFn: () => fetchProjects(page()),
33 placeholderData: keepPreviousData,
34 }))
35β
36 return (
37 <div>
38 <Switch>
39 <Match when={projectsQuery.isPending}>
40 <div>Loading...</div>
41 </Match>
42 <Match when={projectsQuery.isError}>
43 <div>Error: {projectsQuery.error.message}</div>
44 </Match>
45 <Match when={projectsQuery.isSuccess}>
46 <div>
47 <For each={projectsQuery.data.projects}>
48 {(project) => <p>{project.name}</p>}
49 </For>
50 </div>
51 </Match>
52 </Switch>
53 <span>Current Page: {page() + 1}</span>
54 <button
55 onClick={() => setPage((old) => Math.max(old - 1, 0))}
56 disabled={page() === 0}
57 >
58 Previous Page
59 </button>
60 <button
61 onClick={() => {
62 if (!projectsQuery.isPlaceholderData && projectsQuery.data?.hasMore) {
63 setPage((old) => old + 1)
64 }
65 }}
66 // Disable the Next Page button until we know a next page is available
67 disabled={
68 projectsQuery.isPlaceholderData || !projectsQuery.data?.hasMore
69 }
70 >
71 Next Page
72 </button>
73 <Show when={projectsQuery.isFetching}>
74 <span> Loading...</span>
75 </Show>
76 </div>
77 )
78}
79```
80β
81[//]: # 'Example2'