gridcn2.0.0
Server pagination

Keep pages in URL

Store the page and the page size of a server-paged grid in the URL, so a reload or a shared link opens the same page.

A server-paged grid holds its page in memory. A reload shows page 1 again. useDataGridUrlPagination keeps page and pageSize in the URL and hands back the controlled pair that useDataGridServerRows accepts in pages mode.

Install data-grid-url-state and data-grid-server, and wrap your app in a NuqsAdapter. See URL state.

pnpm dlx shadcn@latest add @gridcn/data-grid-url-state
pnpm dlx shadcn@latest add @gridcn/data-grid-server

Sync the page with the URL

  1. Call useDataGridUrlPagination before the server hook.
  2. Spread its result into useDataGridServerRows.
  3. Render the pager from server.pager.

This grid reads its page from the URL and fetches that 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";
import {
  useDataGridUrlPagination,
} from "@/components/data-grid-url-state/data-grid-url-state";

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

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

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

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

Open ?page=3&pageSize=50 and the grid fetches rows [100, 150).

What the URL holds

  • page is 1-based and leaves the URL at page 1.
  • When pageSize equals defaultPageSize (the first of pageSizeOptions, 10 by default), it leaves the URL.
  • A bad page falls back to 1. A bad pageSize, or one outside pageSizeOptions, falls back to defaultPageSize. A link cannot force an unbounded fetch.
  • Every write uses history: "replace". Paging adds no browser history entries.
  • prefix namespaces the keys, so two grids on one page keep separate pages.

Pages that reset

A change of the page size, the sort, the filter, or the search text resets page to 1.

A link to a page past the last page requests that page first. When the row count arrives, the pager moves to the last page and writes it to the URL.

With your own fetch and useDataGridServerPager in place of useDataGridServerRows, the URL hook cannot see your filters. Call url.onPageChange(1) where you handle a filter change.

To keep the sort, filter, and search in the URL too, compose the grid with DataGridProvider and DataGridRoot. Mount <DataGridUrlState> inside the provider and list "filter" and "search" in its spec, because the default is ["sort"]. The first request then carries the restored spec and the restored page together. A restored spec does not cause a second request. See URL state.

This grid restores the page and the spec from the URL:

"use client";

import {
  DataGridBody,
  DataGridHeader,
  DataGridProvider,
  DataGridRoot,
  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";
import {
  DataGridUrlState,
  useDataGridUrlPagination,
} from "@/components/data-grid-url-state/data-grid-url-state";

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

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

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

  return (
    <DataGridProvider {...server.providerProps} columns={columns}>
      <DataGridUrlState spec={["sort", "filter", "search"]} />
      <DataGridRoot {...server.rootProps} className="h-96">
        <DataGridHeader />
        <DataGridBody />
      </DataGridRoot>
      <DataGridPaginationBar {...server.pager} />
    </DataGridProvider>
  );
}

On this page