NeuTronas
NeuTronas

Reputation: 273

MUI DataGrid onCellEditStop returns old value

I am trying to use an editing API from "@mui/x-data-grid" and simply have editing on the cell and retrieve the new value.

When I use

onCellEditStop={(params: GridCellEditStopParams, event: MuiEvent) => {
  console.log(params);
  if (params.reason === GridCellEditStopReasons.cellFocusOut) {
    event.defaultMuiPrevented = true;
  }
}}

Console log prints out the old parameters which include the old value of the cell instead of the new one to which it was changed.

How do I retrieve a new value after editing the cell?

Upvotes: 4

Views: 6992

Answers (4)

Yuelong Li
Yuelong Li

Reputation: 11

In the newest version of MUI (MUI 6), you will need to use value setter in GridColumns definition for that purpose (https://mui.com/x/react-data-grid/editing/#value-parser-and-value-setter).

const gridColumns=[
    {
        field: 'fieldName',
        editable:true,
        valueSetter:(params: GridValueSetterParams)=>{
            let value = params.value; //<-- this contains the new value
            let oldValue = params.row.fieldName;//<-- this contains the old value
            if(value!=oldValue){
                // Do something with the changes
            }
            return params.row
        }
    },...]

Upvotes: 1

Tony
Tony

Reputation: 1

This works for me with @mui/x-data-grid v6:

const handleCellEditStop = (params: GridCellParams, event: MuiEvent) => {
  const { id, field } = params;
  setTimeout(() => {
    params.value = apiRef.current.getCellValue(id, field);
  }, 100)

  console.log('stop', { params });
};

Upvotes: 0

Shylesh S
Shylesh S

Reputation: 17

@mui/x-data-grid v6: When you're editing cells, you might notice that the params object returns the old values from your array. To get the updated cell value, use the following solution instead.

onCellEditStop={(params, event) => {
  const newValue = event.target.value;//here is the new value
}

Upvotes: -1

Mihail Vratchanski
Mihail Vratchanski

Reputation: 439

The callback that you need is onCellEditCommit:

onCellEditCommit={(params: GridCellEditCommitParams, event: MuiEvent) => {
  console.log(params);
  if (params.reason === GridCellEditStopReasons.cellFocusOut) {
    event.defaultMuiPrevented = true;
  }
}}

Demo: https://codesandbox.io/s/datagriddemo-material-demo-forked-i9iz3f?file=/demo.tsx:1661-1677

The property that will have the new value is value, formatted value will show the previous value if available.

Upvotes: 1

Related Questions