Load server rows
Step 2 of 5
Fetch one page of rows from your API with useDataGridServerRows and show it with a pager, so the grid never holds the whole result.
Before you start, compare the data modes and pick pages mode. Install the server add-on. It brings the pager with it:
pnpm dlx shadcn@latest add @gridcn/data-grid-server
useDataGridServerRows calls your fetchRows function once for each page. The grid shows the rows you return. This step wires one page of rows and a pager.
Fetch a page
- Pass
fetchRowstouseDataGridServerRows. If the row id is not in theidfield, passgetRowIdtoo. - In
fetchRows, sendpage,pageSize, andspecto your API. - Resolve with
rowsandtotalRowCount. - Spread
server.gridPropsontoDataGridandserver.pageronto the pager.
The next steps reuse two small files. orders.ts holds the row type and the columns:
import { defineColumns } from "@/components/data-grid/data-grid";
export type Order = { id: string; customer: string; total: number };
export const columns = defineColumns<Order>()([
{ id: "customer", header: "Customer", accessorKey: "customer" },
{ id: "total", header: "Total", accessorKey: "total", type: "number" },
]);api.ts holds the calls to your API. notify shows a message to the user:
import type { DataChange } from "@/components/data-grid/data-grid";
import type {
ServerRowsPageRequest,
} from "@/components/data-grid-server/data-grid-server";
import type { Order } from "./orders";
export async function loadPage(
{ spec, page, pageSize, signal }: ServerRowsPageRequest,
) {
const response = await fetch("/api/orders/query", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ spec, page, pageSize }),
signal,
});
const answer = await response.json();
return {
rows: answer.rows as Order[],
totalRowCount: answer.total as number,
};
}
export async function sendChange(change: DataChange<Order>) {
const response = await fetch("/api/orders/changes", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(change.ops),
});
if (!response.ok) throw new Error("Save refused");
}
export function notify(message: string) {
window.alert(message);
}This grid loads orders with loadPage:
"use client";
import { DataGrid } 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 { columns, type Order } from "./orders";
import { loadPage } from "./api";
export function OrdersGrid() {
const server = useDataGridServerRows<Order>({
fetchRows: loadPage,
});
return (
<>
<DataGrid {...server.gridProps} columns={columns} className="h-96" />
<DataGridPaginationBar {...server.pager} />
</>
);
}What your API receives and returns
specholds the sort, the filters, and the search text. It is untrusted input. On the server, check it withparseServerSpec: it returns a boundedServerSpecor throwsServerSpecError. See Query server rows and the Drizzle example.startandendgive the same page as a row range.end - startispageSize.- After a change of the page, the page size, or the spec, the hook aborts
signal. rowsholds at mostpageSizerows. The hook drops the extra rows and warns in development.totalRowCountis the size of the whole result. The pager reads it.
Give every row a unique id. getRowId defaults to the id field of the row. A repeated id keeps its first row only.
Result
The grid shows 10 rows, because the default page size is the first of pageSizeOptions. The pager shows the page and the row count. A click on Next fetches the next page. A change of the sort, the filter, or the search text goes back to page 1.
Next: Plan server saves.
Related
Compare data modes
Pick the data mode that fits your rows, from a local array to server pages or scroll mode, and see what each mode needs from your API.
Plan server saves
Choose how onSave answers your server, from a full revert to a refetch, a per-row refusal, or an error on one cell, and wire the first save.