Blog>
Snippets

Setting Up Server-side Pagination

Provides a code example of how to configure server-side pagination in React TanStack Table, including fetching data for the current page, handling page changes, and displaying loading states.
import { useQuery } from 'react-query';
import React, { useState } from 'react';
import axios from 'axios';
Imports necessary libraries and hooks.
const fetchData = async (page, limit) => {
  const response = await axios.get(`http://localhost:3004/users?_page=${page}&_limit=${limit}`);
  return response.data;
};
Defines an asynchronous function to fetch data from server with pagination.
const PaginatedTable = () => {
  const [page, setPage] = useState(1);
  const [limit, setLimit] = useState(10);
  const { data, isLoading, isError } = useQuery(['users', page, limit], () => fetchData(page, limit), { keepPreviousData: true });
Sets up a PaginatedTable component with state for page and limit. Uses useQuery to fetch data.
if (isLoading) return <div>Loading...</div>;
if (isError) return <div>Error occurred while fetching data</div>;
Handles loading and error states.
return (
    <div>
        <table>
            {/* Table headers and rows rendering */}
        </table>
        <button onClick={() => setPage(old => Math.max(old - 1, 1))} disabled={page === 1}>Previous Page</button>
        <button onClick={() => setPage(old => old + 1)}>Next Page</button>
    </div>
  );
};
Renders table and pagination buttons with event handlers to change page state.
export default PaginatedTable;
Exports the PaginatedTable component.