React Example: Infinite Query With Max Pages
Source URL: https://tanstack.com/query/latest/docs/framework/react/examples/infinite-query-with-max-pages
Search…
K
Auto
Docs
Partners
React
Latest
Search…
K
latest
React
Latest
React Example: Infinite Query With Max Pages
Section titled “React Example: Infinite Query With Max Pages”Code ExplorerCode
Interactive SandboxSandbox
-
src
-
pages
-
api
-
index.tsx
-
-
-
.gitignore
-
README.md
-
next.config.js
-
package.json
-
tsconfig.json
tsx
import React from 'react' import { QueryClient, QueryClientProvider, useInfiniteQuery, } from '@tanstack/react-query' import { ReactQueryDevtools } from '@tanstack/react-query-devtools'
const queryClient = new QueryClient()
export default function App() { return ( ) }
function Example() { const { status, data, error, isFetching, isFetchingNextPage, isFetchingPreviousPage, fetchNextPage, fetchPreviousPage, hasNextPage, hasPreviousPage, } = useInfiniteQuery({ queryKey: ['projects'], queryFn: async ({ pageParam }) => { const response = await fetch(`/api/projects?cursor=${pageParam}`) return await response.json() }, initialPageParam: 0, getPreviousPageParam: (firstPage) => firstPage.previousId ?? undefined, getNextPageParam: (lastPage) => lastPage.nextId ?? undefined, maxPages: 3, })
return ( <h1>Infinite Query with max pages</h1> <h3>4 projects per page</h3> <h3>3 pages max</h3> {status === 'pending' ? ( <p>Loading...</p> ) : status === 'error' ? ( <span>Error: {error.message}</span> ) : ( <> <button onClick={() => fetchPreviousPage()} disabled={!hasPreviousPage || isFetchingPreviousPage} > {isFetchingPreviousPage ? 'Loading more...' : hasPreviousPage ? 'Load Older' : 'Nothing more to load'} </button> {data.pages.map((page) => ( {page.data.map((project) => ( <p style={{ border: '1px solid gray', borderRadius: '5px', padding: '8px', fontSize: '14px', background: `hsla(${project.id * 30}, 60%, 80%, 1)`, }} key={project.id} > {project.name} </p> ))} </React.Fragment> ))} <button onClick={() => fetchNextPage()} disabled={!hasNextPage || isFetchingNextPage} > {isFetchingNextPage ? 'Loading more...' : hasNextPage ? 'Load Newer' : 'Nothing more to load'} </button> {isFetching && !isFetchingNextPage ? 'Background Updating...' : null} </> )} <hr /> ) }[Want to Skip the Docs?
Section titled “[Want to Skip the Docs?”“If you’re serious about really understanding React Query, there’s no better way than with query.gg”—Tanner Linsley
Learn More](https://query.gg?s=tanstack)
