I am using ag-grid react and trying to update the data using the api with: rowNode.setData()
but when I try to read the rowData its not changing...
my code:
import { AgGridReact } from 'ag-grid-react'; // AG Grid Component
import "ag-grid-community/styles/ag-grid.css"; // Mandatory CSS required by the grid
import "ag-grid-community/styles/ag-theme-quartz.css"; // Optional Theme applied to the grid
import { useRef, useState } from 'react';
import { ColDef } from 'ag-grid-community';
const GridExample = () => {
// Row Data: The data to be displayed.
const [rowData, setRowData] = useState([
{ make: "Tesla", model: "Model Y", price: 64950, electric: true, id: '1' },
{ make: "Ford", model: "F-Series", price: 33850, electric: false, id: '2' },
{ make: "Toyota", model: "Corolla", price: 29600, electric: false, id: '3' },
]);
// Column Definitions: Defines the columns to be displayed.
const [colDefs, setColDefs] = useState<ColDef[]>([
{ field: "make", editable: true },
{ field: "model" },
{ field: "price", },
{ field: "electric" }
]);
const gridRef = useRef<AgGridReact>()
return (
// wrapping container with theme & size
<div
className="ag-theme-quartz" // applying the grid theme
style={{ height: 500 }} // the grid will fill the size of the parent container
>
<AgGridReact
ref={gridRef}
rowData={rowData}
columnDefs={colDefs}
getRowId={({ data }) => data.id}
/>
<button onClick={() => {
console.log('rowData', rowData);
}}>print data</button>
<button onClick={() => {
const rowNode = gridRef.current?.api.getRowNode('2')
//This is the row update
rowNode?.setData( { make: "Ford", model: "newModel", price: 33850, electric: false, id: '2' });
}}>update data</button>
</div>
)
}
const App = () => {
return <GridExample />
}
export default App
I took ag-grid's code example and added the rowId and the buttons.
So when I click the update data button, the data on the table will change, but then when I print the data it stayed as before.
I tried using the api.applyTransaction()
and the rowNode.updateData()
but its the same result...
for some reason the rowNode.setDataValue will update rowNode but I can't use it in my project because its no supporting objects.
You should know that AG-Grid won't update your local state if the grid data is internally changed.
You should either use declarative approach (pass rowData prop and update the prop -> setRowData) or use imperative approach (use grid api object and set data manually)
You can also use grid events like rowDataUpdated
to update your state