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.
| Prop | Purpose | Default |
|---|---|---|
data | The rows, controlled by your code | none |
defaultData | The rows, seeded once and then owned by the grid | none |
onDataChange | Fires once per change with the next array and the operations | none |
onSave | Sends a change to a server. Can return a promise | none |
saveTimeoutMs | Refuses a save that has not settled after this many ms | off |
onSaveRejected | Fires after the grid reverted a refused change, or kept it for keep: true | none |
onBeforeDeleteRows | Runs before a row delete and can cancel it | none |
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
| Field | Meaning |
|---|---|
ops | The operations of the change |
source | What caused the change |
label | A name for the history entry, such as "Add row" |
reverts | On a "rollback" or "merge" change, the change it undoes |
serverRowIds | On 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.
| Operation | Fields |
|---|---|
update | rowId, row, prev, and cells |
insert | rowId, row, index |
delete | rowId, row, index |
move | rowId, 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
source | Cause |
|---|---|
edit | A committed cell edit |
paste | A paste |
fill | A fill |
delete | The delete of the cell contents in a range |
cut | A cut |
row-operation | A row insert, delete, duplicate, or move |
import | The import dialog's append, or a change you apply with commitChange and tag as an import |
history | An undo or a redo |
rollback | The revert of a refused save |
merge | The change that resolveSaveConflict commits on top of the server row. onSave receives it, and history does not record it |
id-swap | actions.replaceRowId or actions.replaceRowIds. onSave does not receive it, and history does not record it |
stream | A batch from updateCells or updateRows, or a deleteRows call with source: "stream" |
replace | A batch from find and replace |
app | A change you apply with the history record function |
Order and effects
- Inside the handler, a write action such as
updateCellsstarts fromnext. Withdata, callsetData(next)first. - A write that another callback makes during a grid write emits its own
onDataChangeafter the outer one. onDataChangeruns after the write. If it throws, the change stays written, andonSaveand the plugin observers still run. The grid hands the error toreportErrorand 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 }.signalaborts when the grid unmounts orsaveTimeoutMsruns out. - A promise that resolves with nothing accepts the change.
- A promise that resolves with
{ rejected }refuses the listed rows or cells. Each entry holdsrowIdand can holdcolumnId,message, andcurrent.currentis 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 ignorescurrent. A refused delete restores the row. A refused insert removes it. - A promise that rejects refuses the whole change. A save that outlives
saveTimeoutMsis refused withreason: "timeout". A throw insideonSaverefuses the whole change too. - The revert of a refused save runs on a
readOnlygrid too. A rejection withkeep: trueleaves the value and marks its cells withmessageinstead.
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.