Keep edits in state
Step 5 of 8
Hold the rows in your own React state with data and onDataChange, then add undo and redo with useDataGridState.
Before you start, finish edit cells. Then install the undo add-on:
pnpm dlx shadcn@latest add @gridcn/data-grid-history
defaultData seeds the grid once, and the grid then owns the rows. When your code needs the rows, for example to save them, pass data instead. This step moves the rows into React state, then adds undo and redo.
Pass data and onDataChange
data puts the rows in your code. The grid shows an edit at once and calls onDataChange with the new array. Every edit, paste, fill, and delete reaches your array only through onDataChange. If you do not store the new array, the grid drops the edit the next time it reads your data. A development build warns once when a write reaches controlled data and neither onDataChange nor onSave is set.
Replace people-grid.tsx with this file:
"use client";
import { useState } from "react";
import { DataGrid } from "@/components/data-grid/data-grid";
import { columns, type Person } from "./columns";
const initialPeople: readonly Person[] = [
{ id: "1", name: "Ada Lovelace", age: 28, active: true },
{ id: "2", name: "Grace Hopper", age: 34, active: true },
{ id: "3", name: "Margaret Hamilton", age: 31, active: false },
];
export function PeopleGrid() {
const [people, setPeople] = useState(initialPeople);
return (
<DataGrid
data={people}
columns={columns}
onDataChange={(next) => setPeople(next)}
aria-label="People"
className="h-96"
/>
);
}onDataChange(next, change) fires once per user gesture. One edit, one paste, one fill, and one delete of a range each fire it once. next is the whole array. change holds the operations (ops) of the gesture and its source, such as "edit" or "paste".
If you pass both data and defaultData, data wins.
Add undo and redo
useDataGridState owns the rows array and the undo history. It passes the rows to the grid as data on every render. It replaces your own state, so do not pass data beside it. Replace people-grid.tsx with this file:
"use client";
import { DataGrid } from "@/components/data-grid/data-grid";
import {
useDataGridState,
} from "@/components/data-grid-history/data-grid-history";
import { columns, type Person } from "./columns";
const initialPeople: Person[] = [
{ id: "1", name: "Ada Lovelace", age: 28, active: true },
{ id: "2", name: "Grace Hopper", age: 34, active: true },
{ id: "3", name: "Margaret Hamilton", age: 31, active: false },
];
export function PeopleGrid() {
const grid = useDataGridState(initialPeople);
return (
<DataGrid
{...grid}
columns={columns}
aria-label="People"
className="h-96"
/>
);
}Result: edit a cell, then press Ctrl/Cmd+Z. The cell returns to its earlier value. Ctrl/Cmd+Y or Ctrl/Cmd+Shift+Z redoes the edit.
grid.history holds canUndo, canRedo, undo, and redo for your own buttons. To send changes to a server, see Save edits.
Next: Select and paste.