How to get values of row after edit for MUI data grid?

Viewed 5010

I am trying to get the values thatI just edited from mui data-grid. My use case is that i would like to be able to take these values and update the state/send a request to update a database.

I have tried using onEditRowsModelChange and onRowEditStop properties but onEditRowsModelChange updates too frequently for my needs and onRowEditStop returns the previous values but not the most recent updated ones. The values are also in a form that is requires parsing to get to.

has anyone had any experience with this?

4 Answers

You can use OnCellEditCommit

<DataGridPro
    rows={rows}
    columns={columns}
    onCellEditCommit={handleRowEditCommit}
/>

your handleRowEditCommit function will look like this

    const handleRowEditCommit = React.useCallback(
        (params) => {
            const id = params.id;
            const key = params.field;
            const value = params.value; },
        []
    );

You can get the details of committed row using apiRef.

I have managed this situation like below:

const apiRef = useGridApiRef();
    
const onRowEditCommit = (id, event) => {
     let row = apiRef.current.getEditRowsModel();
     handleRowEdit(row);
}

I hope it helps.

I have a rather ugly solution using the onEditRowsModelChange method. It does some debouncing and parsing as you mentioned:

let timer;
const handleEditRowsModelChange = (model) => {
        if(timer) clearTimeout(timer);
        timer = setTimeout(() => {
            setEditRowsModel(model);
            let siteId = Object.keys(model)[0];
            let field = siteId ? Object.keys(model[siteId])[0] : null;
            let value = field ? model[siteId][field].value : null;
            siteId && field && (
                sites.forEach(site => {
                    if (site.id == siteId) { 
                        if (site[field] != value) {
                            site[field] = value;
                            sendSiteForEdit(site);
                        }
                    };
                }
            ));
        }, 1500);
};

With default edit mode (cell edit mode) you have to use the onCellEditCommit

const onCellEditCommit= (cellData) => {
    const { id, field, value } = cellData;
    ...
}


<DataGrid 
    onCellEditCommit={onCellEditCommit}
    ...

With row edit mode, you can use the processRowUpdate but make sure you're using experimentalFeatures={{ newEditingApi: true }} with the datagrid

const processRowUpdate = (newRow) => {
    const updatedRow = { ...newRow, isNew: false };
    ...
    return updatedRow;
};


<DataGrid 
    editMode="row"
    processRowUpdate={processRowUpdate}
    experimentalFeatures={{ newEditingApi: true }}
    ...
Related