What I need: I'm using MUI DataGrid > 5. I need that the data that is filled in a cell change automatically the state (onChange). At this moment, I have an useEffect that is listening to these changes to “enable/disable” the “Save” and “Cancel” buttons.
What I tried: Using onCellEditCommit property, it saves the cell content only when I click outside the DataGrid component (or when I press tab or enter). I would like to save the content on cell change.
...
import {
DataGrid,
GridColDef,
GridPreProcessEditCellProps,
GridRowId,
} from "@mui/x-data-grid";
...
const [devices, setDevices] = useState<Device[]>(formValues.devices);
const columns: GridColDef[] = [
{
field: "id",
headerName: "ID",
flex: 10,
},
{
field: "uniqueIdentification",
headerName: "Unique ID",
editable: true,
flex: 30,
},
{
field: "description",
headerName: "Description",
editable: true,
flex: 50,
},
{
field: "isActive",
headerName: "Active",
type: "boolean",
editable: true,
flex: 10,
},
{
field: "actions",
type: "actions",
headerName: "Actions",
width: 100,
cellClassName: "actions",
renderCell: (params) => (
<Box id={`${params.id}`} component="div">
<IconButton
title="Remove"
onClick={() => deleteRow(params.id)}
size="small"
>
<DeleteIcon />
</IconButton>
</Box>
),
},
];
function saveDeviceCell(params) {
const oldDevices = [...devices];
const rowDeviceIndex = oldDevices.findIndex((dev) => dev.id === params.id);
oldDevices[rowDeviceIndex] = {
...oldDevices[rowDeviceIndex],
[params.field]: params.value,
};
setDevices(oldDevices);
}
...
return (
<DataGrid
rows={devices}
columns={columns}
hideFooterPagination
hideFooter
disableSelectionOnClick
autoHeight
onCellEditCommit={saveDeviceCell}
editMode="cell"
/>
...
);