Blog>
Snippets

Implementing Pagination with TanStack Store

Provide a code sample to demonstrate how to implement pagination in a React application using TanStack Store by fetching and displaying pages of data.
import { useQuery } from '@tanstack/react-query';
import React, { useState } from 'react';
Import the necessary hooks from React and TanStack Query.
const fetchProjects = async (page = 1) => {
  const res = await fetch(`https://example.com/api/projects?page=${page}`);
  return res.json();
};
Define the fetchProjects function to fetch data from your API. Adjust the URL to match your API endpoint.
const Projects = () => {
  const [page, setPage] = useState(1);
  const { isLoading, error, data } = useQuery(['projects', page], () => fetchProjects(page));
Create the Projects component and use the useQuery hook to fetch projects. The query is re-executed when the page state changes.
if (isLoading) return 'Loading...';
  if (error) return 'An error has occurred: ' + error.message;
Handle loading and error states.
return (
    <div>
      {data.projects.map(project => (
        <p key={project.id}>{project.name}</p>
      ))}
      <button onClick={() => setPage(old => Math.max(old - 1, 1))}>Previous Page</button>
      <button onClick={() => setPage(old => old + 1)}>Next Page</button>
    </div>
  );
};
Render the projects and provide buttons to navigate between pages.
export default Projects;
Export the Projects component for use in your application.