gridcn2.0.0
Save to a server

Show errors on cells

Paint a server rejection on the exact cell it names with setCellErrors, keep the value, and clear the error when the user fixes it.

A server can reject a value after the grid committed it, for example with a 422 that names the field. actions.setCellErrors marks that cell with the same ring and tint as a rejected validate call. The value stays in the grid.

Set a Quantity above 100 and press Enter: the fake server rejects it after ~600ms and the cell is marked with a red ring — hover it to read the message.

Item
Quantity
Status
Widget
12
ok
Gadget
40
ok
Gizmo
8
ok
Doohickey
25
ok
Thingamajig
60
ok
Server errors: 0

Mark the cells that the server rejected

  1. In onSave, take actions from the second argument.
  2. Read the field errors of the 422 answer and map them to { rowId, columnId, message } entries.
  3. Call actions.setCellErrors with the entries.

The server answers a 422 with { "errors": [{ "rowId": "o-17", "field": "email", "message": "Not an address" }] }:

import {
  DataGrid,
  type DataChange,
  type SaveContext,
} from "@/components/data-grid/data-grid";
import { columns, type Order } from "./orders";

type FieldError = { rowId: string; field: string; message: string };

export function OrdersGrid({ rows }: { rows: Order[] }) {
  async function onSave(change: DataChange<Order>, { actions }: SaveContext) {
    const response = await fetch("/api/orders", {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify(change.ops),
    });
    if (response.status === 422) {
      const { errors }: { errors: FieldError[] } = await response.json();
      actions.setCellErrors(
        errors.map(({ rowId, field, message }) => ({
          rowId,
          columnId: field,
          message,
        })),
      );
      return;
    }
    if (!response.ok) throw new Error(`Save failed: ${response.status}`);
  }

  return (
    <DataGrid
      defaultData={rows}
      columns={columns}
      getRowId={(row) => row.id}
      onSave={onSave}
    />
  );
}

Because the handler returns normally after a 422, the onSave promise resolves and the grid keeps the value. If it throws, the grid reverts the whole change. See Revert or refetch after a save.

What the user sees

  • The cell shows the ring, the tint, and aria-invalid. The message is the aria-description of the cell.
  • Hover the cell to read the message in a tooltip.
  • Open the cell for editing to read the message under the editor.
  • A live validate rejection of the open edit wins over the stored message.

When the error clears

When the user commits a new value to a cell, its error clears. An edit, paste, fill, updateCells, or cell clear (the Delete key) clears it. Clearing the selection keeps the errors. The server can set the error again for a value that is still wrong.

A row that leaves data loses its errors. A refused save that reverts a cell also clears the error of that cell.

To clear errors yourself, pass the targets. Without targets, the call clears every cell error. Render this button inside DataGridProvider, next to DataGridRoot. Select server rows shows that layout:

import { useDataGridActions } from "@/components/data-grid/data-grid";

export function ClearErrorsButton() {
  const actions = useDataGridActions();
  return (
    <button onClick={() => actions.clearCellErrors()}>Clear all</button>
  );
}

setCellErrors merges per cell. An entry for another cell survives. Calling it with an empty list does nothing.

Read the errors

useDataGridCellErrors() returns a ReadonlyMap<string, string> of messages. Build a key with cellErrorKey(rowId, columnId). Render the component inside DataGridProvider, next to DataGridRoot:

import {
  cellErrorKey,
  useDataGridCellErrors,
} from "@/components/data-grid/data-grid";

export function EmailError({ rowId }: { rowId: string }) {
  const errors = useDataGridCellErrors();
  return <span>{errors.get(cellErrorKey(rowId, "email"))}</span>;
}

setCellErrors and clearCellErrors never touch data. They fire no onDataChange, and the history add-on does not record them.

On this page