gridcn2.0.0
Events and state

Data change events

Read every edit, paste, fill, and row change as row-id operations, and send each change to a server with onSave.

onDataChange reports each change to the rows as a list of operations. onSave sends the same change to a server. onBeforeDeleteRows can stop a delete.

PropPurposeDefault
dataThe rows, controlled by your codenone
defaultDataThe rows, seeded once and then owned by the gridnone
onDataChangeFires once per change with the next array and the operationsnone
onSaveSends a change to a server. Can return a promisenone
saveTimeoutMsRefuses a save that has not settled after this many msoff
onSaveRejectedFires after the grid reverted a refused change, or kept it for keep: truenone
onBeforeDeleteRowsRuns before a row delete and can cancel itnone

onDataChange

The callback fires once per change, after the grid stores the next array. One user gesture is one change. Examples are a cell edit, a paste, a fill, a range delete, a row move, and a row insert, delete, or duplicate. The payload holds the next array and a DataChange:

import { useState } from "react";
import { DataGrid, defineColumns } from "@/components/data-grid/data-grid";

type Row = { id: string; name: string };

const columns = defineColumns<Row>()([
  { id: "name", header: "Name", accessorKey: "name" },
]);

function Grid({ initial }: { initial: Row[] }) {
  const [rows, setRows] = useState<readonly Row[]>(initial);
  return (
    <DataGrid
      data={rows}
      columns={columns}
      onDataChange={(next, change) => {
        setRows(next);
        console.log(change.source, change.ops.length);
      }}
    />
  );
}

With data, you own the array and pass next back. Store next as it is: a copy makes the grid rebuild its row id map and its view on every change. With defaultData, the grid has already applied the change and the callback only reports. Pass one of the two. If you pass both, data wins and development mode warns once. The grid ignores later changes to defaultData.

DataChange

FieldMeaning
opsThe operations of the change
sourceWhat caused the change
labelA name for the history entry, such as "Add row"
revertsOn a "rollback" or "merge" change, the change it undoes
serverRowIdsOn a change that took server content, the ids of those rows

Each operation addresses a row by rowId, because row ids survive sorts and filters and view indexes do not.

OperationFields
updaterowId, row, prev, and cells
insertrowId, row, index
deleterowId, row, index
moverowId, row, from, to, and beforeRowId and afterRowId when the row has a neighbor

An update carries cells (columnId, value, prev) for an edit, a paste, or a fill. A whole-row update has no cells. The index of a delete and the from of a move are positions before the whole change. The index of an insert and the to of a move are positions in the result. beforeRowId and afterRowId name the rows that follow and precede the moved row in the result. A move that commitChange applies without neighbor ids, such as an undo or a redo, gets both ids from the rows after the batch.

An insert index past the end puts the row last. Apply the operations of one change together, for example with applyChange. The operation engine contract has the rules.

Sources

sourceCause
editA committed cell edit
pasteA paste
fillA fill
deleteThe delete of the cell contents in a range
cutA cut
row-operationA row insert, delete, duplicate, or move
importThe import dialog's append, or a change you apply with commitChange and tag as an import
historyAn undo or a redo
rollbackThe revert of a refused save
mergeThe change that resolveSaveConflict commits on top of the server row. onSave receives it, and history does not record it
id-swapactions.replaceRowId or actions.replaceRowIds. onSave does not receive it, and history does not record it
streamA batch from updateCells or updateRows, or a deleteRows call with source: "stream"
replaceA batch from find and replace
appA change you apply with the history record function

Order and effects

  • Inside the handler, a write action such as updateCells starts from next. With data, call setData(next) first.
  • A write that another callback makes during a grid write emits its own onDataChange after the outer one.
  • onDataChange runs after the write. If it throws, the change stays written, and onSave and the plugin observers still run. The grid hands the error to reportError and does not rethrow.
  • A row delete from a gesture or an action clears the checked rows of the view, the cell range, and the active cell. If an open edit survives the delete, the selection moves to the edited cell. A row insert and a duplicate keep the active cell on its row.

onSave

onSave runs once per change, after onDataChange and before the plugin observers. It never receives a "rollback", "stream", or "id-swap" change. Return a promise to acknowledge the change. This sample saves each change and throws on a failed request. Pass it as onSave={save}:

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

type Row = { id: string; name: string };

async function save(change: DataChange<Row>) {
  const response = await fetch("/api/rows", {
    method: "POST",
    body: JSON.stringify(change.ops),
  });
  if (!response.ok) throw new Error("Save failed");
}
  • The second argument is { actions, signal }. signal aborts when the grid unmounts or saveTimeoutMs runs out.
  • A promise that resolves with nothing accepts the change.
  • A promise that resolves with { rejected } refuses the listed rows or cells. Each entry holds rowId and can hold columnId, message, and current. current is the row as the server holds it. The revert puts it in place of the refused row. While a newer write to the row is pending, the grid ignores current. A refused delete restores the row. A refused insert removes it.
  • A promise that rejects refuses the whole change. A save that outlives saveTimeoutMs is refused with reason: "timeout". A throw inside onSave refuses the whole change too.
  • The revert of a refused save runs on a readOnly grid too. A rejection with keep: true leaves the value and marks its cells with message instead.

useDataGridRowSaveStatus(rowId) reads the RowSaveStatus of one row. The row carries data-save-status="saving" while the promise is pending. The grid reverts each refused entry through onDataChange with source: "rollback". A refused row shows data-save-status="failed".

resolveSaveConflict({ rowId, mine, theirs, change, message, signal }) decides what a refused row becomes when the server sent current. See Handle refused saves.

actions.replaceRowId(oldId, row) swaps a client id for the server id. See Save edits.

onSaveRejected

The callback fires once per refused change, after the revert. It receives a SaveRejectedContext: { change, rejected, error }. When the promise resolved with { rejected }, error is null. The grid logs a throw inside the callback and isolates it.

onBeforeDeleteRows

The callback runs before every row delete that the grid starts: the delete shortcut, the context menu item, deleteRows, and deleteRowsAt. It does not run for deleteRows with source: "stream". It receives { rowIds, hiddenCount, signal }. rowIds are the rows that go. hiddenCount counts the hidden checked rows that stay. Return false, or a promise of false, to cancel.

A second delete aborts the pending one, and onGateAborted reports "superseded". A throw or a rejection cancels the delete, and onRowActionSkipped reports "gate-threw". A promise that resolves with false reports "gate-declined". If the grid became readOnly, or the rows or the checked rows changed while the promise was pending, the grid drops a confirmed delete.

On this page