On top of how to edit a particular row in material-ui table?, whenever I am clicking on the X icon while editing a row, the changes still reflecting in the table. Is there any way to overcome it? The edited record should only save on check (_/) icon. I am fully blank on this now.
Playground: https://codesandbox.io/s/material-ui-editable-tables-wsp0c?file=/package.json:0-677
CodePudding user response:
The example you provided shows that onChange() overrides the rows:
setRows(newRows);
My suggestion would be to create a draft copy of the edited row (since only one can be edited at the same time). Then overwrite the actual data with the draft if you click "approve" otherwise do nothing. The behavior you describe is really just the custom logic in the code, there is nothing MUI-specific about it. You will best learn how to do it if you do it on your own. I can check your example though.
CodePudding user response:
The problem is in your onToggleEditMode
method. You are preserving the previous value fine during the onChange
handler, and you are replacing the temporary value with the previous one during the onRevert
handler properly. However, in that onRevert
handler, you update the rows state with setRows
and then call the onToggleEditMode
function directly after, which still references the stale rows state object.
const onToggleEditMode = id => {
setRows(state => {
return rows.map(row => {
if (row.id === id) {
return { ...row, isEditMode: !row.isEditMode };
}
return row;
});
});
};
You need to use that state
parameter on the second line so that you do not override the new value you just saved and create a race condition. I updated the method to the following, (I also cleaned up the row map method) and it worked in the sandbox:
const onToggleEditMode = (id) => {
setRows((state) =>
state.map((row) => ({
...row,
isEditMode: row.id === id ? !row.isEditMode : row.isEditMode
}))
);
}