ShakibDShy

Server-side Pagination

Implementing server-side pagination with React Pagination Pro

Example

Server-side Pagination

Pagination with server-side data fetching

Loaded 0 items

function ServerSideExample() {
  const [items, setItems] = useState<typeof ITEMS>([]);
  const [loading, setLoading] = useState(false);
 
  // Simulate API call
  const fetchItems = async (page: number, pageSize: number) => {
    setLoading(true);
    try {
      // In a real application, this would be an API call
      await new Promise((resolve) => setTimeout(resolve, 1000));
      const start = (page - 1) * pageSize;
      const end = start + pageSize;
      setItems(ITEMS.slice(start, end));
    } finally {
      setLoading(false);
    }
  };
 
  return (
    <div className="space-y-4">
      <div className="rounded-lg border p-4">
        {loading ? (
          <p>Loading...</p>
        ) : (
          <p>Loaded {items.length} items</p>
        )}
      </div>
 
      <Pagination
        totalItems={100}
        defaultPageSize={10}
        mode="server"
        isLoading={loading}
        onPageChange={fetchItems}
      />
    </div>
  );
}

Implementation Guide

1. Set Server Mode

Enable server-side mode by setting the mode prop to 'server':

<Pagination mode="server" />

2. Handle Loading States

Use the isLoading prop to show loading states:

<Pagination isLoading={loading} />

3. Implement Data Fetching

Use the onPageChange callback to fetch data:

async function fetchData(page: number, pageSize: number) {
  const response = await fetch(
    `/api/items?page=${page}&pageSize=${pageSize}`
  );
  return response.json();
}
 
<Pagination
  onPageChange={fetchData}
  // ...other props
/>

Best Practices

  1. Error Handling
function ServerPagination() {
  const [error, setError] = useState<Error | null>(null);
 
  async function fetchData(page: number, pageSize: number) {
    try {
      setError(null);
      const data = await fetchItems(page, pageSize);
      setItems(data);
    } catch (err) {
      setError(err as Error);
    }
  }
 
  return (
    <>
      {error && (
        <div className="text-red-500">
          Error: {error.message}
        </div>
      )}
      <Pagination
        onPageChange={fetchData}
        // ...other props
      />
    </>
  );
}
  1. Caching
function CachedPagination() {
  const cache = useRef<Record<string, any>>({});
 
  async function fetchWithCache(page: number, pageSize: number) {
    const key = `${page}-${pageSize}`;
    if (cache.current[key]) {
      return cache.current[key];
    }
 
    const data = await fetchItems(page, pageSize);
    cache.current[key] = data;
    return data;
  }
 
  return (
    <Pagination
      onPageChange={fetchWithCache}
      // ...other props
    />
  );
}
  1. Debouncing
import { useMemo } from 'react';
import debounce from 'lodash/debounce';
 
function DebouncedPagination() {
  const debouncedFetch = useMemo(
    () => debounce(fetchItems, 300),
    []
  );
 
  return (
    <Pagination
      onPageChange={debouncedFetch}
      // ...other props
    />
  );
}

API Integration Tips

  1. URL Parameters: Keep URL in sync with pagination state
  2. Response Format: Structure API response with metadata
  3. Error States: Handle network errors gracefully
  4. Loading States: Show appropriate loading indicators
  5. Cache Management: Implement caching when appropriate

Example API Response

{
  "items": [...],
  "metadata": {
    "currentPage": 1,
    "pageSize": 10,
    "totalItems": 100,
    "totalPages": 10
  }
}

Last updated on

On this page