Move from client rows to server rows
Replace a local data array with useDataGridServerRows, and check each grid feature that changes when your server owns the rows.
A grid with a local data array sorts, filters, and copies every row in the browser. When the browser cannot hold the result, your server must own it. This page replaces data with useDataGridServerRows and lists each feature that changes. Each line links the page that owns the detail.
Before you start, pick pages mode or scroll mode on Compare data modes. Then install the server add-on:
pnpm dlx shadcn@latest add @gridcn/data-grid-server
Replace the data
- Put the rows behind an API that takes the spec and a page or a row range. Server rows contract has the request and the answer.
- Remove
data,defaultData, andonDataChangefrom the grid. - Pass
fetchRowstouseDataGridServerRows. MovegetRowIdinto the hook options too, unless the row id is in theidfield. - Move
onSaveinto the hook options. Move your ownonDataChangethere too. - Spread
server.gridPropsontoDataGrid. Keepcolumnsand your other props. - In pages mode, spread
server.pagerontoDataGridPaginationBar.
This grid fetches blocks of orders in place of a local data array:
"use client";
import {
DataGrid,
defineColumns,
type DataChange,
} from "@/components/data-grid/data-grid";
import {
useDataGridServerRows,
} from "@/components/data-grid-server/data-grid-server";
type Order = { id: string; customer: string; total: number };
const columns = defineColumns<Order>()([
{ id: "customer", header: "Customer", accessorKey: "customer" },
{ id: "total", header: "Total", accessorKey: "total", type: "number" },
]);
async function save(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 OrdersGrid() {
const server = useDataGridServerRows<Order>({
mode: "scroll",
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 };
},
onSave: save,
});
return <DataGrid {...server.gridProps} columns={columns} className="h-96" />;
}The hook sets sortMode="server", filterMode="server", totalRowCount, and checkedRowsLifetime="across-filters" in gridProps.
Check what changes
| Feature | Local array | Server rows |
|---|---|---|
| Sort | The grid sorts data. sortCompare and the cell type compare the values. | Your server sorts. sortCompare does not run. |
| Filter | The grid runs filter.match and the operators. | Your server filters. filter.match does not run. Without fetchFilterValues, the header filter lists the values of the loaded rows. |
| Quick search | Highlights matches in every row. | Puts the text in spec.searchText. The box highlights matches in the rows that come back. |
| Copy and paste | Every displayed row. On a paged grid, the shown page. | The rows that data holds. In scroll mode, a copy gives empty cells for rows that are not loaded, and a paste skips them. |
| Checked rows | The checks cover data. | actions.selectAllMatching() checks the whole result. Send useDataGridSelectedRows() to your server. |
| Export | Writes every row. | Writes the rows the grid holds. Pass a source to write the whole result. |
| Totals | useDataGridAggregate totals every row. | DataGridServerAggregateReporter asks your server for the totals. |
| Saves | onSave on the grid. | onSave in the hook options. The hook fetches again after the saves settle. |
| Undo and redo | Writes the old values to data. | An undo is one more change that onSave sends. |
| Row operations | Change data. | Send each insert, delete, and move to your API. |
| Live pushes | updateCells keeps the row in place and sets viewStale. reconcileView() or reorder: "immediate" moves it. | The row keeps its place and turns stale. Call server.reshape(), or set reshapeDelayMs, so that the server places it again. |
| URL state | <DataGridUrlState> restores the sort, and the filter and search text when its spec lists them. | <DataGridUrlState> restores the spec, and the first request of the hook carries it. Your server applies it. |
Check the server
- Treat the request as untrusted input. Pass
body.specthroughparseServerSpec, and bound the page or the row range. See Check the spec on your server. - Port each custom
sortCompareandfilter.matchto your query. The grid does not run them in server mode. - Make the sort order unique. See Sort on the server.
- Answer with
totalRowCount. A source without a count answers withnextCursororhasMore. See Load without row count.
Test the move
- Sort and filter each column that you sorted or filtered before. Compare the order with the old client result.
- Scroll or page to the end. Check the row count and the last row.
- Edit, paste, and undo a cell. Check that the change reaches your API, and that a refusal reverts the cell. See Handle refused saves.
- Make a request fail. Check the error state and the Retry button. See Recover from load errors.
- Check all matching rows, uncheck one, and send the selection to your server.
- Export the whole result through a
source.
Result: the grid shows the rows of your server, and each feature you use has a server path.
Related
- Compare data modes: pick the mode
- Data mode support: each feature in each mode
- Query server rows: the spec on the server
- Troubleshoot server data: rows, counts, and saves that go wrong