Query server rows
Send the sort, filter, and search text of the grid to your server, and show the rows that come back.
When your server owns the result, it must also sort, filter, and search it. The grid tracks what the user chose, which is the spec: sorts, filters, and searchText. useDataGridServerRows sends the spec to your fetchRows function with every request. The rows you return are the rows the grid shows.
1,000 rows match · fetching…
Send the spec
- Read
specinfetchRowsand send it to your API. - Apply the spec on the server.
- Answer with the matching rows in order and the row count of the result.
This grid sends the spec as JSON:
"use client";
import { DataGrid, defineColumns } 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" },
]);
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 };
},
});
return (
<DataGrid
{...server.gridProps}
columns={columns}
className="h-96"
/>
);
}The hook sets sortMode="server", filterMode="server", and headerClickBehavior="sort". The grid tracks the spec and never sorts or filters data itself. Treat the spec as untrusted input. Pass it through parseServerSpec before you build a query. See Check the spec and the ORM examples, such as the Drizzle example.
A client sort or filter cannot see rows the grid never fetched. Use the hook, or set sortMode="server" and filterMode="server" yourself. The grid warns once in development when a client sort or filter changes while data holds unloaded rows or fewer rows than totalRowCount.
Pages mode takes the same spec. A spec change there goes back to page 1 and fetches again. In scroll mode it starts the blocks over.
Check the spec on your server
parseServerSpec(body, { columns, limits }) from data-grid-server turns an untrusted request body into a bounded, typed ServerSpec. It throws a ServerSpecError with the path of the bad part, for example filters[2].value. It checks the column ids and the operators of each column. It checks the value shapes, the depth of the filter tree, and the number of sorts, filters, and groups. It checks the length of every value.
It drops every key it does not know and builds no query. It does not read start and end. Your server bounds them, as this sample does:
import {
parseServerSpec,
ServerSpecError,
} from "@/components/data-grid-server/data-grid-server";
// The blockSize of the hook: one request asks for at most one block.
const MAX_ROWS = 50;
const MAX_BODY_CHARS = 64 * 1024;
const toIndex = (value: unknown) => {
const index = Math.floor(Number(value));
return Number.isSafeInteger(index) && index >= 0 ? index : 0;
};
export async function POST(request: Request) {
const text = await request.text();
if (text.length > MAX_BODY_CHARS) {
return Response.json({ error: "Body too large" }, { status: 413 });
}
try {
const body = JSON.parse(text);
const spec = parseServerSpec(body.spec, { columns: ["customer", "total"] });
// map spec.sorts, spec.filters, and spec.searchText to your query layer
const start = toIndex(body.start);
const end = Math.max(start, Math.min(toIndex(body.end), start + MAX_ROWS));
return Response.json(await queryOrders(spec, start, end));
} catch (error) {
if (error instanceof ServerSpecError || error instanceof SyntaxError) {
return Response.json({ error: error.message }, { status: 400 });
}
throw error;
}
}columns is a list of ids, or a map from id to rules: sortable, filterable, operators, and customOperators. customOperators maps each custom operator id to its value shape: "none", "single", "range", or "list". A list of ids rejects every custom operator. limits sets maxSorts (64), maxFilters (64), maxGroups (16), maxValueLength (1000), maxListLength (1000), and maxSearchLength (500).
Sort on the server
The grid shows the sort cycle, aria-sort, the sort indicator, and DataGridSortList. It calls onSortChange and never reorders data. The order of your answer is the displayed order.
In scroll mode, a sort change drops the loaded rows, because fetched blocks hold the old order. The hook fetches block 0 again with the new spec.
With server.gridProps, a header click sorts. Without totalRowCount, a header click selects the column until you set headerClickBehavior="sort".
Make the sort order unique, for example by adding the row id as the last sort key. The hook keeps the first row of a repeated row id. In random access, scroll mode leaves the later copy as a skeleton row. A sequential source and pages mode drop it.
Filter on the server
The grid tracks the filter spec: the filter menu, the header filters, and data-filtered. It calls onFilterChange and never removes a row from data.
- A filter change discards the loaded rows. In scroll mode, fetched blocks hold rows of the old spec. The hook starts over at block 0 and takes the new row count from the answer.
- A newer spec wins. The hook aborts the requests of the old spec and ignores their answers.
- The header filter lists values from your server. Pass
fetchFilterValuesto list every value of a column, not only the loaded ones. See Server values.
Search on the server
The quick-search box highlights and navigates matches in the rows the grid holds. It never narrows the rows. The hook puts the text in spec.searchText. Your server can narrow the rows by it, and the box then highlights the rows that come back.
Control the spec
The hook owns the spec. Seed it with defaultSpec. Control it with spec and onSpecChange. A change of the spec content starts the requests over. In pages mode, the change also goes back to page 1, unless no answer has landed yet.
serverSpecKey(spec) returns the spec as a string without the generated filter ids. Use it as a query key or an effect dependency. ServerSpec and serverSpecKey import from the data-grid barrel.
Related
- Server rows contract: the request and the answer
- Sorting: the sort props
- Filtering: the filter props
- URL state: restore the spec from a link
- Load rows while scrolling: the scroll mode