I'm trying to add new bubble in the chart whenever we click on add button I am able to update the state of data i.e. Chartdata using usestate hook but the chart does not re-render and does not show the chart according to the new updated data.
const data =
{
datasets: [{
label: 'Grapefruit',
data: [{
x: 10,
y: 40,
r: 40
}
],
backgroundColor: 'rgb(255, 99, 132)'
},
{
label: 'Lime',
data: [{
x: 23,
y: 37,
r: 40
}
],
backgroundColor: 'rgb(0, 152, 102)'
}
]
};
const App = () => {
const [chartData, setchartData] = useState(data);
function callingChart(inputText,value)
{
const newl = [{x: data.datasets[1].data[0].x + l,y:data.datasets[1].data[0].y+ l,r:data.datasets[1].data[0].r + l}]
data.datasets.push({ label: inputText,
data: newl,
backgroundColor: 'rgb(255, 128, 0)'})
setchartData(data);
}
return (
<div className ="bubble">
<BarChart data={chartData} options={options}/>
</div>
);
}
export default App;
I don't know what I'm doing wrong .
From what I can tell you are mutating the
dataobject, which is a reference to the same object you initialized yourchartDatastate to, and then save the mutateddataobject back into thechartDatastate.In React you necessarily need to shallow copy all state that is being update. Create a
newChartDataobject from the currentchartDatastate and shallow copy the root properties, then declare a newdatasetsarray by shallow copying the previous state'sdatasetsarray. This is a new array reference that you can push new values into.