Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading