gridcn2.0.0
Server pagination

Load rows by page

Fetch one page of rows per request from your server, show a pager, and keep the page, the sort, the filter, and the row count in step.

When your server returns one page of rows per request, use useDataGridServerRows in pages mode. The hook calls your fetchRows for the current page and returns a pager for the footer. If the browser holds the whole array, see Client pagination.

sort, filter, search and paging are all server-side
Loading…
Name
Email
Role
Score
Page 1
pnpm dlx shadcn@latest add @gridcn/data-grid-server

Fetch a page

  1. Send start, end, and spec (the sort, the filters, and the search text) from fetchRows to your API.
  2. Answer with the rows of that page and the row count of the whole result.
  3. Spread server.gridProps onto the grid and server.pager onto DataGridPaginationBar.

This grid loads 25 orders per page:

"use client";

import { DataGrid, defineColumns } from "@/components/data-grid/data-grid";
import { DataGridPaginationBar } from "@/components/data-grid-pagination/data-grid-pagination";
import { useDataGridServerRows } from "@/components/data-grid-server/data-grid-server";

type Order = { id: string; customer: string };

const columns = defineColumns<Order>()([
  { id: "customer", header: "Customer", accessorKey: "customer" },
]);

export function OrdersGrid() {
  const server = useDataGridServerRows<Order>({
    defaultPageSize: 25,
    fetchRows: async ({ start, end, spec, signal }) => {
      const response = await fetch("/api/orders", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ start, end, spec }),
        signal,
      });
      const answer = await response.json();
      return { rows: answer.rows, totalRowCount: answer.total };
    },
  });

  return (
    <>
      <DataGrid {...server.gridProps} columns={columns} className="h-96" />
      <DataGridPaginationBar {...server.pager} />
    </>
  );
}

On page 3 at 25 rows per page, start is 50 and end is 75. The request also carries page and pageSize. Pass signal to fetch, so the hook can abort a replaced request.

The hook sets sortMode="server" and filterMode="server": your server applies spec. See Query server rows.

Control the page

The hook keeps the page and the page size in its own state. defaultPage and defaultPageSize seed them once. To control a value, pass page with onPageChange, or pageSize with onPageSizeChange, as Keep pages in URL does. The page resets in these cases:

  • A change of the page size, the sort, the filter, or the search text goes back to page 1.
  • A spec that URL state restores before the first answer keeps the page of the link.
  • A count that shrinks below the page moves the pager to the last page. A count of 0 leaves the page unchanged.

Show the count

totalRowCount is the row count of the filtered result. The hook also passes it to the grid with checkedRowsLifetime="across-filters", so checked rows survive a page change. See Select server rows.

If your server sends no count, answer { rows, hasMore } and omit totalRowCount, or send totalRowCount: null. The footer then shows "Page 3" in place of a range, Next stays enabled while hasMore is true, and Last stays disabled. Without hasMore, a full page means that another page exists. For a cursor API, see Tune page loading.

When the last pending insert or delete settles, the hook loads the page again, unless refreshAfterSave is false. Then call refresh().

Fetch the pages yourself

If you fetch with your own code, call useDataGridServerPager for the footer. It keeps no page state, so you control page and pageSize. Spread gridProps onto the grid: its totalRowCount sets sortMode and filterMode to "server". Control sortState, filterState, and searchText, and send them with each request.

If the page, the page size, the sort, the filters, or the search text change, this grid fetches again:

"use client";

import { useEffect, useState } from "react";
import {
  DataGrid,
  defineColumns,
  type FilterNode,
  type SortSpec,
} from "@/components/data-grid/data-grid";
import {
  DataGridPaginationBar,
  useDataGridServerPager,
} from "@/components/data-grid-pagination/data-grid-pagination";

type Order = { id: string; customer: string };
type Spec = { sorts: SortSpec[]; filters: FilterNode[]; searchText: string };
const NO_SPEC: Spec = { sorts: [], filters: [], searchText: "" };

const PAGE_SIZE = 25;
const columns = defineColumns<Order>()([
  { id: "customer", header: "Customer", accessorKey: "customer" },
]);

export function OrdersGrid() {
  const [page, setPage] = useState(1);
  const [spec, setSpec] = useState<Spec>(NO_SPEC);
  const [rows, setRows] = useState<readonly Order[]>([]);
  const [total, setTotal] = useState<number | null>(null);

  useEffect(() => {
    const controller = new AbortController();
    fetch("/api/orders", {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ page, pageSize: PAGE_SIZE, ...spec }),
      signal: controller.signal,
    })
      .then((response) => response.json())
      .then((answer) => {
        setRows(answer.rows);
        setTotal(answer.total);
      })
      .catch((error) => controller.signal.aborted || console.error(error));
    return () => controller.abort();
  }, [page, spec]);

  function changeSpec(change: Partial<Spec>) {
    setSpec({ ...spec, ...change });
    setPage(1);
  }

  const { gridProps } = useDataGridServerPager({
    page,
    pageSize: PAGE_SIZE,
    totalRowCount: total,
    onPageChange: setPage,
  });

  return (
    <>
      <DataGrid
        data={rows}
        columns={columns}
        getRowId={(row) => row.id}
        sortState={spec.sorts}
        onSortChange={(sorts) => changeSpec({ sorts })}
        filterState={spec.filters}
        onFilterChange={(filters) => changeSpec({ filters })}
        searchText={spec.searchText}
        onSearchTextChange={(searchText) => changeSpec({ searchText })}
        {...gridProps}
        className="h-96"
      />
      <DataGridPaginationBar />
    </>
  );
}

The controller aborts the request of a replaced page.

On this page