Aditya Rohilla
Aditya Rohilla

Reputation: 337

Line Chart not updating everytime

So I am using Line from react-chartjs-2 and I've added an onClick event to the labels which blur all the lines except the current one.

Here is my onClick function code:

legend:{
             'onClick': function(e, legendItem) {
                var index = legendItem.datasetIndex;
                var ci = this.chart;

                console.log(ci.data.datasets);
                //var alreadyHidden = (ci.data.datasets[index].borderColor === ci.data.datasets[index].accentFadedColor) ? false : true;


                for(var i=0; i< ci.data.datasets.length;i++){
                  if (i !== index) {
                      ci.data.datasets[i].borderColor = ci.data.datasets[i].accentFadedColor;
                  } else if (i == index){
                    ci.data.datasets[i].borderColor = ci.data.datasets[i].accentColor;
                  }
                }

                that.updateValue(index);

                ci.update();

              }

The problem is, the function updates the chart on first click but not after that. Though I can see the updates values with console.log()

Any idea what I am doing wrong?


Update:

So apparently my chart is working fine. Inside the onClick() I'm making call to another function ( which sets state ) which is causing this behavior.

Here's a link to stackblitz

Any advice?

Upvotes: 1

Views: 319

Answers (1)

Aditya Rohilla
Aditya Rohilla

Reputation: 337

So apparently, just making the function call inside onClick() but before updating the datasets solved the problem.

I think rendering after setState and canvas update were somehow mixing up.

Here's the updated code:

legend:{
             'onClick': function(e, legendItem) {
                var index = legendItem.datasetIndex;
                var ci = this.chart;
                that.updateValue(index);
                for(var i=0; i< ci.data.datasets.length;i++){
                  if (i !== index) {
                      ci.data.datasets[i].borderColor = ci.data.datasets[i].accentFadedColor;
                      ci.data.datasets[i].lineWidth = ci.data.datasets[i].highlightedWidth;
                  } else if (i == index){
                    ci.data.datasets[i].borderColor = ci.data.datasets[i].accentColor;
                    ci.data.datasets[i].lineWidth = ci.data.datasets[i].fadedWidth;

                  }
                }
              ci.update();                }

Upvotes: 1

Related Questions