gridcn2.0.0
Contracts

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.

ConcernRule
ModesPass totalRowCount, or set sortMode="server" and filterMode="server".
Sort, filter, searchThe grid shows the spec and never changes data.
Pages or scrollBoth modes of useDataGridServerRows take the same spec.
CountsPass the filtered totalRowCount, or null.
SavesonSave resolves with the refused rows.
RacesDrop the answer of a replaced request.
Request checkRun 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

  1. Read the spec from the grid. Use the store hooks (useDataGridSortState, useDataGridFilterState) or the controlled pairs (sortState and onSortChange).
  2. Send the spec to your API. Make one request for each view state.
  3. Pass the answer as data. Pass the count to the pager as totalRowCount, and pass the same count to the provider as totalRowCount (null when the server sends none). A totalRowCount makes sortMode and filterMode default to "server", so a spec restored at mount never sorts or filters the window on the client. Set sortMode="client" or filterMode="client" to override one. A grid without totalRowCount keeps 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] : [],
  );
}

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 modeScroll mode
The grid showsOne page at a timeOne continuous list of totalRowCount rows
You sendpage, pageSize, start, end, a cursor on a cursor source, and the specstart, end, a cursor on a cursor source, and the spec
The answer holdsThe rows of one page, and the filtered totalRowCount, hasMore, or nextCursorThe rows of one block, and totalRowCount or nextCursor
After a spec changeGo to page 1 and refetchReset the loaded rows and refetch
Stale requestsfetchRows receives an AbortSignal that aborts a replaced requestThe 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 } to useDataGridServerRows, or pass useDataGridServerPager({ page, pageSize, totalRowCount: null, hasMore, onPageChange }). The footer shows "Page N" and enables Next while hasMore is 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, gridProps carries totalRowCount: null until 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.

On this page