I have used https://www.npmjs.com/package/react-chartjs-2, and it displays a chart with data in the first time. But whenever I try to redraw, using new data and datasets it always displays previous graph data on a chart.
I have tried solutions from: https://github.com/reactchartjs/react-chartjs-2
Also tried to give reference
But still, it shows the same data which it loads the first time.
Code to display chart,
<Line
data={graphData}
redraw
options={options}
height="100px"
weight="100px"
/>
In this, graphData is, const [graphData, setGraphData] = useState(data);
redraw,
I have also tried to do, redraw={true}
When the data will be modified, I use
setGraphData(updatedData)
to update the chart, I have also checked whether data is changed or not.
Data in graphData updates but not displayed on graph
Where the data which is assign as a default data for graphData,
const data = {
labels: months,
datasets: [
{
label: "# of Users",
data: [0, 64, 129, 193, 258, 322, 387, 451, 516, 580],
fill: false,
backgroundColor: "rgb(255, 99, 132)",
borderColor: "rgba(255, 99, 132, 0.2)",
yAxisID: "y-axis-1",
},
{
label: "# of Orders",
data: [0, 25, 50, 76, 101, 126, 151, 177, 202, 227],
fill: false,
backgroundColor: "rgb(54, 162, 235)",
borderColor: "rgba(54, 162, 235, 0.2)",
yAxisID: "y-axis-2",
},
],
};
I am creating copy of this data and then assigning in setGraphData()
Anyone can Help me with this! Thank you in advance!!
Without seeing the code, there is only one solution here. Provide a key to the chart component & update the key once the data is updated,
<chart key={getKey()} data={data} />
The get key will create a unique key with respect to the new data.
const getKey = () => {
return data?.map((p) => p.id)?.join();
};
The only thing important here is that the getKey method should return a new value if the data is updated JSON.stringify(data)
is the simplest option(I am not sure if it is a good approach to provide the serialized data as key, but surely it will work)