Show totals from a server
Pin a totals row that your server computes for the whole filtered result, in pages mode, scroll mode, and with your own API.
A server grid holds one page or some blocks, so aggregateRow cannot total the whole result. serverAggregateRow asks your server instead. It calls fetchAggregates with the current spec and shows the values as a row in a pinned band.
pnpm dlx shadcn@latest add @gridcn/data-grid-pinned-rows
Fetch the totals
- Declare the row with
serverAggregateRow. An inline row is fine: the band calls the newestfetchAggregates. - Resolve
{ [columnId]: value }infetchAggregatesfor the whole result ofspec. - Pass the row to
useDataGridPinnedRows.
This grid pins the totals of the filtered result:
"use client";
import {
DataGridBody,
DataGridHeader,
DataGridProvider,
DataGridRoot,
defineColumns,
} from "@/components/data-grid/data-grid";
import {
serverAggregateRow,
useDataGridPinnedRows,
} from "@/components/data-grid-pinned-rows/data-grid-pinned-rows";
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 post(url: string, body: unknown, signal: AbortSignal) {
const request = { method: "POST", body: JSON.stringify(body), signal };
return (await fetch(url, request)).json();
}
const TOTALS = serverAggregateRow({
cells: { id: "__totals__", customer: "Total" },
fetchAggregates: ({ spec, signal }) => {
const { filters, searchText } = spec;
return post("/api/orders/totals", { filters, searchText }, signal);
},
});
export function OrdersGrid() {
const { plugin } = useDataGridPinnedRows({ bottomRows: [TOTALS] });
const server = useDataGridServerRows<Order>({
mode: "scroll",
plugins: [plugin],
fetchRows: async ({ start, end, spec, signal }) => {
const answer = await post("/api/orders", { start, end, spec }, signal);
return { rows: answer.rows, totalRowCount: answer.total };
},
});
return (
<DataGridProvider {...server.providerProps} columns={columns}>
<DataGridRoot {...server.rootProps}>
<DataGridHeader />
<DataGridBody />
</DataGridRoot>
</DataGridProvider>
);
}The server answers { "total": 1234.5 }: one value for each requested column id, computed over the whole result that filters and searchText select. The band dims while the values load, go stale, or fail. See Show the status. Pass status to useDataGridPinnedRows to set the band status yourself.
Read the result yourself
useDataGridPinnedRows returns serverAggregates: the result of each serverAggregateRow entry, top band first, in entry order. The result holds row, status, error, loading, refresh(), and retry(). It stays PENDING_SERVER_AGGREGATE until the band mounts.
Read it to show the status or a refresh button outside the band:
export function OrdersGrid() {
const { plugin, serverAggregates } = useDataGridPinnedRows({
bottomRows: [
serverAggregateRow({
fetchAggregates: ({ spec: { filters, searchText }, signal }) =>
post("/api/orders/totals", { filters, searchText }, signal),
}),
],
});
const totals = serverAggregates[0];
// server, DataGridProvider, and the header and body as above
return (
<>
{/* the grid as above */}
<button type="button" onClick={totals.refresh}>
Totals: {totals.status}
</button>
</>
);
}To place the totals row yourself, render DataGridServerAggregateReporter inside DataGridProvider. It takes the options of serverAggregateRow and an onChange that receives the result. Start the state from PENDING_SERVER_AGGREGATE and pass totals.row as a plain pinned row. Inside the grid, useDataGridServerAggregate(options) returns the same result.
Refresh after a save
serverAggregateRow, DataGridServerAggregateReporter, and useDataGridServerAggregate fetch again after the last pending save settles. An edit that your onSave answers with a promise therefore updates the totals. Set refreshAfterSave: false to keep the totals of the last request, and call refresh() on the result yourself.
A grid without onSave has no save to wait for. Call totals.refresh() after your own write lands. totals is an entry of serverAggregates.
When it requests
The request carries the spec and not the rows in the grid. The same code serves pages mode, scroll mode, a controlled spec, and your own API.
- The row requests once on mount.
- It requests again after each filter, quick-search, or
columnIdschange, after the saves in flight settle, and afterrefresh()andretry(). - Each request waits
debounceMsbefore it starts, the one on mount too. - A sort does not change the totals, so it does not request.
- A newer request aborts the older one through
signal, and the grid drops a late answer of the older one.
Show the status
status tells the band what to show:
| Status | Meaning |
|---|---|
"loading" | No values yet. |
"stale" | The old values stay while a newer request runs. |
"ready" | The values match the spec. |
"error" | The last request failed. The old values stay. onError fires once per failure. |
A band with a status other than "ready" dims. A band that loads or goes stale sets aria-busy. Every band also carries a data-status attribute. loading is true for "loading" and "stale". refresh() requests again and keeps the old values on screen. retry() requests again after an error and does nothing otherwise.
Options
| Option | Default | Effect |
|---|---|---|
fetchAggregates | required | Resolves the values for a { spec, columnIds, signal } request. |
columnIds | every column | The columns to ask for. |
debounceMs | 150 | Milliseconds to wait before each request starts. 0 starts it at once. |
onError | none | Called once per failed request. |
cells | none | Fixed cell values by column id, such as the id and a label. |
refreshAfterSave | "settled" | false skips the fetch after saves. The reporter and the hook take it too. |
The answer is untrusted. The hook keeps values only for the requested columns. It cuts text at 1000 characters and drops everything but text, finite numbers, booleans, and null. An answer that is not an object counts as an error. The band formats each value with the cell type of its column, so a number column shows the total as a number.
Related
- Pinned rows: the bands and the totals of loaded rows
- Pinned rows options: every option
- Server rows contract: the spec that
fetchAggregatesreceives - Data mode support: the features per data mode
Group server rows
Let your server group a large result, so the grid loads the groups of one level and the rows of the groups the user opens.
Troubleshoot server data
Find the cause of missing rows, a wrong page count, lost edits, or a lost selection in a grid that loads rows from your server, and fix it.