Search code examples
javascriptreactjstypescriptag-grid

AgGrid Unable To Restore Original Grid Data


I populate the grid after an intial API call. One of the fields is editiable - Price

If i edit a Price cell, and click the Restore button, the original dataset is applied.

If i edit a Price cell again, the Restore no longer works.

Example: https://stackblitz.com/edit/ag-grid-react-hello-world-agjiy2?file=index.js

Code:

import React, { useState, useEffect, useRef } from 'react';
import { render } from 'react-dom';
import { AgGridReact } from 'ag-grid-react';

import 'ag-grid-community/styles/ag-grid.css';
import 'ag-grid-community/styles/ag-theme-alpine.css';

const myPromise = new Promise((resolve, reject) => {
  setTimeout(() => {
    resolve(
      [
        { make: 'Toyota', model: 'Celica', price: 35000 },
        { make: 'Ford', model: 'Mondeo', price: 32000 },
        { make: 'Porsche', model: 'Boxter', price: 72000 },
      ]
    );
  }, 300);
});

 
const App = () => {
  const [rowData, setRowData] = useState([]);
  const initData = useRef([]);

  const [columnDefs] = useState([
    { field: 'make' },
    { field: 'model' },
    { field: 'price', editable: true },
  ]);

  useEffect(() => {
    let data = myPromise
      .then((data) => {
        console.log(data);
        setRowData(data);
        initData.current = JSON.parse(JSON.stringify(data));
      });
  }, []);

  const restore = () => {
    setRowData(initData.current);
  }

  return (
    <div>
      <button onClick={restore}>Back to original</button>

      <br></br>

      <div className="ag-theme-alpine" style={{ height: 400, width: 600 }}>
        <AgGridReact rowData={rowData} columnDefs={columnDefs}></AgGridReact>
      </div>

    </div>
  );
};

Solution

  • Change your restore method like that

    const restore = () => {
      console.log('initData', initData)
      var obj = JSON.parse(JSON.stringify(initData.current))
      setRowData(obj);
    }
    

    It's happening because you modify your object after your edit action. To prevent it modifying, get a deep copy of your initData object and use it.

    Playground:

    https://stackblitz.com/edit/ag-grid-react-hello-world-fnxqdy?file=index.js