Server rows example
Send sort, filter, search, and page to your server with one fetchRows function, and see stale-request aborts, server pushes, and revalidation.
useDataGridServerRows owns the sort, filter, search text, page, and page size of a server grid. You write the one fetchRows function that calls your API. The hook fetches a page for each state and aborts a request that a newer state replaces. It goes back to page 1 when the spec or the page size changes. It keeps the last good rows on screen while the next page loads. The grid sorts and filters nothing itself.
In the demo, the Pages and Scroll buttons switch the mode of the hook. Sort a header, filter, search, and page. Each change sends one request to a fake server with about 300 ms of latency.
pnpm dlx shadcn@latest add @gridcn/data-grid-server-side-demo
What the demo shows
- Pages and Scroll switch the
modeof the hook. Pages mode setsprefetchNextPage, so Next shows the next page with no wait. - Revalidate every 10 s sets
revalidateIntervalMsand fetches the rows again on that timer. See Tune row retention. - Server pushes changes three scores every 500 ms with
updateRows. A row whose score the sort reads keeps its place and carriesdata-row-stale(the demo dims it) until a refresh places it. See Push into a server-ordered view. - The Reshape select sets
reshapeDelayMs. With Reshape off (reshapeDelayMs: false), a refresh places the pushed rows. With Reshape 1 s, the hook refreshes one second after the pushes. - Delete on server removes the first row on the server and deletes it in the grid with
source: "stream". - The grid starts sorted by Score, highest first.
The wiring
This grid loads orders by page and saves edits through onSave:
import { DataGrid, defineColumns } from "@/components/data-grid/data-grid";
import type { DataChange } 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" },
]);
async function saveOrders(change: DataChange<Order>) {
const response = await fetch("/api/orders", {
method: "POST",
body: JSON.stringify(change.ops),
});
if (!response.ok) throw new Error(`Save failed: ${response.status}`);
}
export function OrdersGrid() {
const server = useDataGridServerRows<Order>({
onSave: saveOrders,
fetchRows: async ({ spec, page, pageSize, signal }) => {
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, totalRowCount: answer.total };
},
});
return (
<>
<DataGrid
{...server.gridProps}
columns={columns}
className="h-96"
/>
<DataGridPaginationBar {...server.pager} />
</>
);
}The request and the answer
- The request holds
spec(sorts,filters,searchText),page,pageSize,start,end,cursor, andsignal.startis(page - 1) * pageSizeandendisstart + pageSize.cursorisundefineduntil an answer returnsnextCursor. fetchRowsresolves{ rows, totalRowCount }. A server without a count resolves{ rows, hasMore }. Server rows options lists how the hook checks an answer.
What gridProps carries
server.gridProps carries these members:
| Member | What it does |
|---|---|
data, totalRowCount | The rows on screen and the row count of the whole result. |
sortMode, filterMode, sortState, filterState, searchText, and their change callbacks | Hand the sort, the filter, and the search to the server, and hold the spec. |
loading, error, onRetry | Show the loading and error states. |
onSave | Runs your onSave. The hook fetches again after the saves settle (refreshAfterSave). |
headerClickBehavior: "sort" | A header click sorts. Set it after the spread to change that. |
getRowId, checkedRowsLifetime: "across-filters" | The row id, and checked rows that stay across pages. |
plugins | The refresh guard of the hook, then your plugins option. |
- A handler or
pluginsprop after the spread joins the hook wiring. AnonSaveprop runs in place of theonSaveoption. - A composed layout spreads
server.providerPropsontoDataGridProviderandserver.rootPropsontoDataGridRoot. The demo does this.
Pass the request through parseServerSpec(body.spec, { columns }) from data-grid-server before you build a query, and cap the request body size. The function throws a ServerSpecError for an invalid spec. The ORM examples call it.
A failed request keeps the last good rows on screen and shows an error state with Retry. See Handle failures. To own the spec or the page, see Query server rows and Load rows by page.
Delay every request
Text inputs in the filter and the search box wait 200 ms (inputDebounceMs) after the last keystroke before they change the spec. To delay every request, wait inside fetchRows. The wait ends when the signal aborts:
import type {
UseDataGridServerRowsOptions,
} from "@/components/data-grid-server/data-grid-server";
type Order = { id: string; customer: string };
const delay = (ms: number, signal: AbortSignal) =>
new Promise<void>((resolve, reject) => {
const timer = setTimeout(resolve, ms);
signal.addEventListener(
"abort",
() => {
clearTimeout(timer);
reject(signal.reason);
},
{ once: true },
);
});
const fetchRows: UseDataGridServerRowsOptions<Order>["fetchRows"] = async ({
spec,
page,
pageSize,
signal,
}) => {
await delay(300, signal);
const response = await fetch("/api/orders/query", {
method: "POST",
body: JSON.stringify({ spec, page, pageSize }),
signal,
});
const answer = await response.json();
return { rows: answer.rows, totalRowCount: answer.total };
};Related
- Server rows contract: the contract for every source
- Server rows options: the options, the request, and the answer
- Query server rows: the sort, filter, and search on the server
- Select server rows: checks across pages
- Drizzle example: this contract in Drizzle code, next to the Prisma and Supabase examples