Hello React Developers:
I'm encountering a problem where a user makes an edit to a specific cell in AG Grid. The table updates fine, and an API call (GET request from Axios) returns the correct array of records. There is a column called "spend", which when updated calls the API to send new values for a column called "plan". The table contains Date, Plan, and Spend columns. Editing "Spend" in the UI updated "Plan" values... these values are sent back to the UI.
But, for some reason, the corresponding chart doesn't update until after another cell in the grid is edited. Please associated code below. If anyone has any ideas, I would appreciate it.
// initial variables
const [gridData, setGridData] = useState([]);
const [spendData, setSpendData] = useState([]);
const [rowData, setRowData] = useState([]);
// this handles the editing of the AG Grid cell. editing is working and updating immediately.
const onCellValueChanged = (params) => {
const updatedRows = [...rowData];
const editedRow = params.data;
const rowIndex = updatedRows.findIndex(row => row.Date === editedRow.Date);
updatedRows[rowIndex] = editedRow;
setRowData(updatedRows);
setSpendData([updatedRows.map(data => data.spend)])
};
// This is the useEffect function
useEffect(() => {refreshData()}, [spendData]);
// This is the API call
const refreshData = React.useCallback(() => {
axios.get('/updatedata', {params: {sp: [spendData]},
})
.then(response => {
setGridData(response.data.records);
});
}, [spendData]
)
// This is the Response body part containing the Victory Chart code
<VictoryChart
<VictoryLine
interpolation="natural"
style={{
data: { stroke: "#fff", strokeWidth: 0.5 }
}}
data = {gridData}
x = 'Date'
y = 'plan'
/>
</VictoryChart>
I like found a solution, but I don't understand why it work. I modified the "onCellValueChanged" to include a var. see below.
now it is working as expected, and updating the chart as soon as the cell edit is entered.