Server rows contract
Run sort, filter, search, and paging in your backend and show the answer in the grid.
A server grid shows the rows your backend returns. The grid tracks what the user chose, which is
the spec: sort, filter, and search text. You send the spec to your API, together with the page or the row range. The answer becomes
data. Two provider props, sortMode="server" and filterMode="server", stop the grid from
sorting and filtering the answer a second time. The Server rows example runs this contract.
| Concern | Rule |
|---|---|
| Modes | Pass totalRowCount, or set sortMode="server" and filterMode="server". |
| Sort, filter, search | The grid shows the spec and never changes data. |
| Pages or scroll | Both modes of useDataGridServerRows take the same spec. |
| Counts | Pass the filtered totalRowCount, or null. |
| Saves | onSave resolves with the refused rows. |
| Races | Drop the answer of a replaced request. |
| Request check | Run parseServerSpec on every request body. |
One hook for server rows
useDataGridServerRows does steps 1 to 3 below and the race guard. It returns gridProps, providerProps, rootProps, spec, totalRowCount, pager, status, loading, error, retry, refresh, and reshape. This sample fetches one page for each spec and renders the pager:
import { DataGrid, defineColumns } 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" },
]);
export function OrdersGrid() {
const server = useDataGridServerRows<Order>({
fetchRows: async ({ start, end, spec, signal }) => {
const res = await fetch("/api/orders", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ start, end, spec }),
signal,
});
const body = await res.json();
return { rows: body.rows, totalRowCount: body.total };
},
});
return (
<>
<DataGrid {...server.gridProps} columns={columns} className="h-96" />
<DataGridPaginationBar {...server.pager} />
</>
);
}The Server rows example shows the full flow.
The contract
- Read the spec from the grid. Use the store hooks (
useDataGridSortState,useDataGridFilterState) or the controlled pairs (sortStateandonSortChange). - Send the spec to your API. Make one request for each view state.
- Pass the answer as
data. Pass the count to the pager astotalRowCount, and pass the same count to the provider astotalRowCount(nullwhen the server sends none). AtotalRowCountmakessortModeandfilterModedefault to"server", so a spec restored at mount never sorts or filters the window on the client. SetsortMode="client"orfilterMode="client"to override one. A grid withouttotalRowCountkeeps the"client"default, so set both props to"server"there.
Set headerClickBehavior="sort" so that a header click sorts. The default, "select", makes a
header click select the column and sort nothing.
Sort
The grid shows the sort indicator and aria-sort, and it calls onSortChange. It never reorders
data. The order of your answer is the displayed order. When the spec changes, refetch:
import { useState } from "react";
import {
DataGridBody,
DataGridHeader,
DataGridProvider,
DataGridRoot,
defineColumns,
type FilterNode,
type SortSpec,
} from "@/components/data-grid/data-grid";
type Order = { id: string; status: string };
const columns = defineColumns<Order>()([
{ id: "status", header: "Status", accessorKey: "status" },
]);
export function OrdersGrid({ first }: { first: Order[] }) {
const [rows, setRows] = useState<readonly Order[]>(first);
const [sorts, setSorts] = useState<SortSpec[]>([]);
const [filters, setFilters] = useState<FilterNode[]>([]);
// Fetch with sorts and filters, then call setRows(answer).
return (
<DataGridProvider
data={rows}
onDataChange={setRows}
columns={columns}
getRowId={(row) => row.id}
sortMode="server"
filterMode="server"
headerClickBehavior="sort"
onSortChange={setSorts}
onFilterChange={setFilters}
>
<DataGridRoot className="h-96">
<DataGridHeader />
<DataGridBody />
</DataGridRoot>
</DataGridProvider>
);
}An edit to a sorted column shows no re-sort hint under sortMode="server". Refetch to get the
new order.
Filter
The grid tracks the filter tree: the filter menu, the header filters, and the data-filtered
indicator all show it. It never removes rows from data. Your backend applies the tree, and the
answer holds the matching rows. The tree is untrusted input. Pass the request through parseServerSpec before
you build a query. It checks the depth, the size, the column ids, the operators, and the value shapes (the ORM examples, such as the Drizzle example, call it). See Query server rows.
The header filter popover and the isAnyOf input of the filter menu list the values of the
loaded rows. Pass fetchFilterValues to list the values of the whole column from your backend. See
Server values.
Check the request on your server
parseServerSpec(input, options) checks a request body against ParseServerSpecOptions. Its columns option lists the ids a request can name, or maps each id to its ServerSpecColumnRules: sortable, filterable, operators, and custom operators. Its limits option is a ServerSpecLimits: maxSorts (64), maxFilters (64), maxGroups (16), maxValueLength (1000), maxListLength (1000), and maxSearchLength (500).
URL state drops a filter value over 1,000 characters and cuts the search text to 500 characters. maxValueLength and maxSearchLength bound them on the server.
The top-level entries combine with "and", or with "or" when the spec holds filterJoin: "or". parseServerSpec reads filterJoin too: "and" or "or". Any other value throws a ServerSpecError at the path filterJoin. The result holds the key only when it is "or", so a spec without it means "and".
A group in filters can hold not: true. Your server returns the rows that fail the group. parseServerSpec reads not as a boolean. Any other value throws a ServerSpecError at the path filters[i].not. The result holds not only when it is true. A cell that is NULL fails every condition except "empty", so the negated group keeps that row. An empty group matches every row, negated or not.
Check a group request
A grouped request adds groupBy and aggregates to the spec, and groupPath and childKind to the request. parseServerSpec reads groupBy (at most maxGroupLevels, 4) and aggregates (at most maxGroupAggregates, 32, one reducer per column). ServerSpecColumnRules takes groupable and aggregatable.
parseGroupPath(body, spec) returns { groupPath, childKind }. The path follows spec.groupBy in order and is not longer. A key is a string of at most maxGroupKeyLength (1,024) characters, a finite number, a boolean, or null. childKind is "groups" while the path is shorter than groupBy, else "rows". Pass every key to your query as a parameter.
Custom operators
A custom operator reaches the spec as a filter with its id in operator. List the id with its value shape, then map it to your query, as this sample shows:
import {
parseServerSpec,
} from "@/components/data-grid-server/data-grid-server";
export function regionFilters(body: { spec: unknown }) {
const spec = parseServerSpec(body.spec, {
columns: { city: { customOperators: { inRegion: "single" } } },
});
// A group holds its own filters; walk it the same way.
return spec.filters.flatMap((node) =>
"operator" in node && node.operator === "inRegion" ? [node.value] : [],
);
}Search
The quick-search box highlights and navigates matches in the loaded rows. It never narrows the
view, in any mode. To search the whole result, send searchText to your fetch. Read it with
useDataGridSearchText, or use the searchText and onSearchTextChange pair. Your answer
holds the matching rows, and the box then highlights them.
Pages or scroll mode
Both modes of useDataGridServerRows take the same spec. They differ in how rows reach the grid.
| Pages mode | Scroll mode | |
|---|---|---|
| The grid shows | One page at a time | One continuous list of totalRowCount rows |
| You send | page, pageSize, start, end, a cursor on a cursor source, and the spec | start, end, a cursor on a cursor source, and the spec |
| The answer holds | The rows of one page, and the filtered totalRowCount, hasMore, or nextCursor | The rows of one block, and totalRowCount or nextCursor |
| After a spec change | Go to page 1 and refetch | Reset the loaded rows and refetch |
| Stale requests | fetchRows receives an AbortSignal that aborts a replaced request | The same AbortSignal |
Set totalRowCount to the filtered count on each filter change. When a smaller count puts page past the last page, the pager
calls your onPageChange once with the clamped page. It skips this while totalRowCount is 0 (Pager options). In scroll mode, a changed spec resets the hook and drops every fetched block. On a random access source, a changed totalRowCount does the same. See
Sorting a scroll grid and
Filtering a scroll grid.
The cell range and the active cell follow their row ids while the rows stay in data. A page
change or refetch that removes a row drops it from the range. Checked rows depend on totalRowCount:
without it, a checked row that leaves data drops out. With it and the default checkedRowsLifetime, the grid
remembers the check by row id and checks the row again when it returns. See
Selection and bulk actions.
Row count and unknown totals
Pass the filtered row count to the provider as totalRowCount. It sizes the "select all" count and
marks data as a window of a larger result. A server that sends no count works in both modes:
- Pages: answer
{ rows, hasMore }touseDataGridServerRows, or passuseDataGridServerPager({ page, pageSize, totalRowCount: null, hasMore, onPageChange }). The footer shows "Page N" and enables Next whilehasMoreis true. See Pager options. - Scroll:
useDataGridServerRows({ mode: "scroll" })loads a cursor chain and grows the list in steps. Answer{ rows, nextCursor }, or{ rows, hasMore }without a cursor. See A source with no total. When the source sends no count,gridPropscarriestotalRowCount: nulluntil the source ends.
Selection and bulk actions
Set totalRowCount (useDataGridServerRows sets it). With totalRowCount, checkedRowsLifetime defaults to "across-filters". Checks then survive page changes, evictions, and server sort
or filter changes, and actions.selectAllMatching() selects the whole result. Render this button inside the DataGridProvider:
import { useDataGridSelectedRows } from "@/components/data-grid/data-grid";
type DeleteProps = {
deleteOrders: (body: object) => Promise<void>;
};
export function DeleteSelected({ deleteOrders }: DeleteProps) {
const selected = useDataGridSelectedRows();
const body =
selected.mode === "ids"
? { ids: selected.ids }
: { spec: selected.spec, exceptIds: selected.excludedIds };
return <button onClick={() => deleteOrders(body)}>Delete</button>;
}Send selected.spec, the spec the selection was made under, with the ids. The server evaluates and bounds both. See
Selection over a server result.
Saving and refusals
Send an edit to your API from onSave(change). Return a promise that resolves with the rows the server
refused. The grid marks the rows saving, reverts only the refused ones, and calls onSaveRejected:
import { useState } from "react";
import {
DataGridBody,
DataGridHeader,
DataGridProvider,
DataGridRoot,
defineColumns,
} from "@/components/data-grid/data-grid";
type Order = { id: string; status: string };
const columns = defineColumns<Order>()([
{ id: "status", header: "Status", accessorKey: "status" },
]);
type SavedProps = {
first: Order[];
save: (ops: object[]) => Promise<{ rowId: string; message?: string }[]>;
notify: (message: string) => void;
};
export function SavedOrders({ first, save, notify }: SavedProps) {
const [rows, setRows] = useState<readonly Order[]>(first);
return (
<DataGridProvider
data={rows}
onDataChange={setRows}
columns={columns}
getRowId={(row) => row.id}
onSave={async (change) => ({ rejected: await save(change.ops) })}
onSaveRejected={({ rejected }) =>
notify(rejected[0]?.message ?? "Refused")
}
>
<DataGridRoot className="h-96">
<DataGridHeader />
<DataGridBody />
</DataGridRoot>
</DataGridProvider>
);
}onSave never receives the revert (source: "rollback"), a server push (source: "stream"), or an id swap (source: "id-swap"). With useDataGridServerRows, pass onSave to the hook and it fetches again after the saves settle (refreshAfterSave).
Pass resolveSaveConflict to merge a refused row with the server row. See Handle refused saves, Save edits, and Fetch with a cache.
Async gates
An async gate holds a paste, an edit start, a row insert, or a row duplicate until your API answers. Cancel async gates lists when the grid drops an answer, and the async gates example runs one.
Races and row identity
When the spec changes twice fast, the older answer can arrive last. Cancel the first request, or ignore the older answer:
import { useEffect } from "react";
type Spec = { sorts: unknown; filters: unknown; searchText: string };
type Page = { rows: { id: string }[] };
export function useFetchedRows(
spec: Spec,
fetchRows: (spec: Spec) => Promise<Page>,
setRows: (rows: Page["rows"]) => void,
) {
useEffect(() => {
let stale = false;
fetchRows(spec).then((res) => {
if (!stale) setRows(res.rows);
});
return () => {
stale = true;
};
}, [spec, fetchRows, setRows]);
}Keep getRowId stable across fetches. Selection, edit state, and row operations follow row ids.
URL state
DataGridUrlState writes the spec from the URL into the grid store on
mount. With both modes set to "server", the store keeps the spec and never sorts or filters the
answer. Your fetch reads the restored spec and loads the rows. With pagination, add
useDataGridUrlPagination for page and pageSize.
Without totalRowCount and without both modes set to "server", a URL-restored spec sorts and
filters partial data in the browser. With totalRowCount, the grid warns once in development when
a client sort or filter runs over fewer rows than totalRowCount.
Related
- Data modes: choose a strategy and a mode.
- Query server rows: the spec props.
- Server rows options: the server pager.
- Load rows while scrolling: windows of rows.
- Server rows example: the query code.