For ag-grid, is it possible to access old rowData?

893 Views Asked by At

I am creating some custom inline editing functionality and am trying to reset the data when the user hit cancel after making edits to specific columns. I'm using cellRenderers for this so I don't have access to the editing params that a cellEditor would.

Currently, what I am doing is saving the specific row's data in React state originalRowInfo when that row is clicked:

const moreInfoClick = (event, toggleMoreInfo, rowData) => {
  event.persist();
  setMoreInfoLocation({ x: event.clientX, y: event.clientY });
  setRowInfo(rowData);
  setOriginalRowInfo({ ...rowData });
  toggleMoreInfo(true);
};

I am getting rowData via params.data when I click on a row

The reason I can't just use the rowInfo state is because that gets changed by ag-grid whenever I make an edit to the column. But using {...rowData} seems to fix that.

My only issue now is one of my column values is an array with objects inside and when I edit that column, it gets changed inside originalRowInfo as well. I would imagine this has something to do with object referencing.

The column looks something like this:

[
  {position: 1, heat_num: 100},
  {position: 2, heat_num: 200}
]

And what actually gets edited is the heat_num

The only thing I can think of is to refetch the data from DB on Cancel but I would rather not have to do that.

1

There are 1 best solutions below

2
On

You don't need originalRowInfo to reset to the original state if the user cancels the editing, but you may rather do the opposite: save the new value inputValue as temporary state when the user editing and:

  • If the user submit the result: call ICellRendererParams.setValue(inputValue) to commit the result.
  • Otherwise, if the user abort: simply discard the result by resetting inputValue to ICellRendererParams.value which is the original value.
function EditableCellRenderer(params: ICellRendererParams) {
  const [editable, setEditable] = React.useState(false);
  const [originalData] = React.useState(params.value);
  const [inputValue, setInputValue] = React.useState(params.value);
  const inputRef = React.useRef(null);
  const onEdit = () => {
    setEditable(true);
    setTimeout(() => {
      inputRef.current?.focus();
    });
  };
  const onCancel = () => {
    setInputValue(originalData);
    setEditable(false);
  };
  const onSubmit = () => {
    params.setValue(inputValue);
    setEditable(false);
  };

  return (
    <>
      <input
        ref={inputRef}
        value={inputValue}
        onChange={(e) => setInputValue(e.target.value)}
        disabled={!editable}
      />
      <button onClick={onEdit}>E</button>
      <button onClick={onCancel}>X</button>
      <button onClick={onSubmit}>S</button>
    </>
  );
}

Live Demo

Edit 64081091/for-ag-grid-is-it-possible-to-access-old-rowdata