[Chartjs]-React ChartJS prevent new data from being added into state after it's redrawn?

2👍

So the problem that you describe is that data is added to your component state when the component is re-rendered. In the code snipped you have supplied, you dont use any of the life cycle methods in React that can be triggered on re-renders. And I cannot see any other hooks that should trigger on a re-render. Therefore I cant find any source to your problem.

However, I can see other issues that might make debugging harder for you. Solving these might help you in nailing down the actual problem. In the componentDidMount method you call functions whose only purpose is to update the state. This is not good design since it will force the component to immediately re-render several times whenever it is mounted.

A better design is to fully prepare the chartData-objekt in the constructor. For example, you could change your chartColors function to take a chartData object as a parameter, and return the new object with colors added. Then make your constructor look something like this:

constructor(props) {

   super(props);
   const chartDataWithoutColors = {
       labels: [],
       datasets: [
         {
           //label: "Quotes",
           data: [],
           backgroundColor: []
         }
       ]
     }

   const chartDataWithColor = this.chartColors(chartDataWithoutColors);

   this.state = {
     chartData: chartDataWithColor
   };
}

By removing unnecessary calls to setState you will make your components life both simpler and more performant. When you have simplified your component, start debugging by removing non-critical parts one at the time and try to nail down when your problem disappears. This should be sufficient to find the bug.

Good luck!

Leave a comment