gridcn2.0.0
Server and data examples

Server pagination example

Fetch one page of rows per request with TanStack Query or SWR, and see the page and page size act as the cache key.

useDataGridServerPager only does the page math. You own page, pageSize, and totalRowCount, and you fetch each page. Both grids below load 25 rows per page from a fake server with about 300 ms of latency. Both write an edit to that server. The grids get the rows of one page and no totalRowCount, so a header sort or filter changes only the shown page. To send the sort and the filter to the server, use Load rows by page with useDataGridServerRows.

TanStack Query

useQuery fetches the page. The page and the page size form the query key, so each page has its own cache entry. placeholderData: keepPreviousData keeps the old page on screen while the next page loads.

Loading page…
Name
Email
Role
Score
No rows
1–25 of 1,000
pnpm dlx shadcn@latest add @gridcn/data-grid-pagination-react-query-demo

This grid keeps an edit in the cached page with onDataChange. onSave sends the change to the server and then invalidates the pages, so the grid shows what the server holds. If the server refuses the request, onSave throws and the grid reverts the edit:

import { useState } from "react";
import {
  keepPreviousData,
  useQuery,
  useQueryClient,
} from "@tanstack/react-query";
import {
  DataGrid,
  defineColumns,
  type DataChange,
} from "@/components/data-grid/data-grid";
import {
  DataGridPaginationBar,
  useDataGridServerPager,
} from "@/components/data-grid-pagination/data-grid-pagination";

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

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

const NO_ROWS: Order[] = [];

export function OrdersGrid() {
  const queryClient = useQueryClient();
  const [page, setPage] = useState(1);
  const [pageSize, setPageSize] = useState(25);

  const query = useQuery({
    queryKey: ["orders", page, pageSize],
    queryFn: async () => {
      const response = await fetch(`/api/orders?page=${page}&size=${pageSize}`);
      return (await response.json()) as { rows: Order[]; total: number };
    },
    placeholderData: keepPreviousData,
  });

  const { pager } = useDataGridServerPager({
    page,
    pageSize,
    totalRowCount: query.data?.total ?? 0,
    onPageChange: setPage,
    onPageSizeChange: (next) => {
      setPageSize(next);
      setPage(1);
    },
  });

  function onDataChange(next: readonly Order[]) {
    queryClient.setQueryData(["orders", page, pageSize], {
      rows: next,
      total: query.data?.total ?? 0,
    });
  }

  async function onSave(change: DataChange<Order>) {
    const response = await fetch("/api/orders", {
      method: "POST",
      body: JSON.stringify(change.ops),
    });
    if (!response.ok) throw new Error("Save refused");
    await queryClient.invalidateQueries({ queryKey: ["orders"] });
  }

  return (
    <>
      <DataGrid
        data={query.data?.rows ?? NO_ROWS}
        columns={columns}
        getRowId={(row) => row.id}
        onDataChange={onDataChange}
        onSave={onSave}
        className="h-96"
      />
      <DataGridPaginationBar {...pager} />
    </>
  );
}

SWR

useSWR fetches the page with the key ["orders", page, pageSize]. The keepPreviousData option keeps the old page on screen while the next page loads. After an edit, the scoped mutate that useSWR returns revalidates the current page.

Loading page…
Name
Email
Role
Score
No rows
1–25 of 1,000
pnpm dlx shadcn@latest add @gridcn/data-grid-pagination-swr-demo

The fetcher of SWR receives the key itself, so the key is a tuple. This hook fetches a page. It exposes the rows and the count of the page on screen, and a revalidate function:

import useSWR from "swr";

type Order = { id: string; customer: string };
type OrdersPage = { rows: Order[]; total: number };

export function useOrdersPage(page: number, pageSize: number) {
  const { data, mutate } = useSWR(
    ["orders", page, pageSize] as [string, number, number],
    async ([, p, size]): Promise<OrdersPage> => {
      const response = await fetch(`/api/orders?page=${p}&size=${size}`);
      return response.json();
    },
    { keepPreviousData: true },
  );

  return {
    rows: data?.rows ?? [],
    total: data?.total ?? 0,
    revalidate: () => mutate(),
  };
}

Pass rows and total to the grid and the pager as in the TanStack Query sample, and call revalidate at the end of onSave.

On this page