Chart.js: [BUG?] How to update a chart by replacing entire data object

Created on 17 Nov 2016  ·  5Comments  ·  Source: chartjs/Chart.js

Expected Behavior

According to https://github.com/chartjs/Chart.js/pull/1646,

You can now change the entire data object of the chart and then call update and the chart will work. The line sample has been update to test this behaviour.
Note to whomever reviews this: please test all chart types before merging.

Current Behavior

Replacing the entire dataobject in a chart and calling update() on the chart, does not update the chart correctly.

Steps to Reproduce

Following the example https://github.com/chartjs/Chart.js/blob/master/samples/line/line.html I created a test.

  1. Open https://jsfiddle.net/mdt86/219hry2s/7/
  2. Click on the button REPLACE ENTIRE DATA OBJECT
  3. Verify that the chart is not updated with the new values (cfr. newDataObject), but only value[0] in the first dataset is updated (see code for reference)
  4. Check lines 132-140 reported here
            console.log(myLine.data);
            // comment out: this one would work, but I want to try a different approach (see following lines)
            // config.data = newDataObject;
            // the newDataObject does not override myLine.data object: why???
                        myLine.data = newDataObject;
            // ... but updating a single value works: why??? 
            myLine.data.datasets[0].data[0] = 1000;
            console.log(myLine.data);
                        window.myLine.update();

Context

Although modifying config.data (cfr. code above) would solve this issue, I would like to understand why calling myLine.data = newDataObject does not work.
My project is indeed quite complex: I create the chart in one place, then I would like to update my chart later on in another place, by calling myLine.data = newDataObject.

Ideas are welcome!

Environment

  • Chart.js version: 2.x (2.4.0 in the test linked above)
  • Browser: Chrome
help wanted bug

Most helpful comment

Because chart.data is an alias to chart.config.data which defines only the getter, not the setter.

All 5 comments

This is probably due to https://github.com/chartjs/Chart.js/blob/master/src/core/core.controller.js#L201-L205

We only provide a getter. @simonbrunel should we provide a setter too?

We could, however you can already replace the data via the chart config: chart.config.data = newData.

Great @simonbrunel, using

myLine.config.data = newDataObject;

works! (see line 136 in new jsfiddle https://jsfiddle.net/mdt86/219hry2s/9/)

Why is it chart.config.data and not chart.data though?

Thanks again!

Because chart.data is an alias to chart.config.data which defines only the getter, not the setter.

I see, thanks a lot again! :+1:

The issue can be closed for me.

Was this page helpful?
0 / 5 - 0 ratings