MCPcopy
hub / github.com/TanStack/query / Example

Function Example

examples/react/infinite-query-with-max-pages/src/pages/index.tsx:19–107  ·  view source on GitHub ↗
()

Source from the content-addressed store, hash-verified

17}
18
19function Example() {
20 const {
21 status,
22 data,
23 error,
24 isFetching,
25 isFetchingNextPage,
26 isFetchingPreviousPage,
27 fetchNextPage,
28 fetchPreviousPage,
29 hasNextPage,
30 hasPreviousPage,
31 } = useInfiniteQuery({
32 queryKey: ['projects'],
33 queryFn: async ({ pageParam }) => {
34 const response = await fetch(`/api/projects?cursor=${pageParam}`)
35 return await response.json()
36 },
37 initialPageParam: 0,
38 getPreviousPageParam: (firstPage) => firstPage.previousId ?? undefined,
39 getNextPageParam: (lastPage) => lastPage.nextId ?? undefined,
40 maxPages: 3,
41 })
42
43 return (
44 <div>
45 <h1>Infinite Query with max pages</h1>
46 <h3>4 projects per page</h3>
47 <h3>3 pages max</h3>
48 {status === 'pending' ? (
49 <p>Loading...</p>
50 ) : status === 'error' ? (
51 <span>Error: {error.message}</span>
52 ) : (
53 <>
54 <div>
55 <button
56 onClick={() => fetchPreviousPage()}
57 disabled={!hasPreviousPage || isFetchingPreviousPage}
58 >
59 {isFetchingPreviousPage
60 ? 'Loading more...'
61 : hasPreviousPage
62 ? 'Load Older'
63 : 'Nothing more to load'}
64 </button>
65 </div>
66 {data.pages.map((page) => (
67 <React.Fragment key={page.nextId}>
68 {page.data.map((project) => (
69 <p
70 style={{
71 border: '1px solid gray',
72 borderRadius: '5px',
73 padding: '8px',
74 fontSize: '14px',
75 background: `hsla(${project.id * 30}, 60%, 80%, 1)`,
76 }}

Callers

nothing calls this directly

Calls 1

useInfiniteQueryFunction · 0.90

Tested by

no test coverage detected

Used in the wild real call sites across dependent graphs

searching dependent graphs…