[Chartjs]-Unexpected error when attempting to update chart data in Chart.js, in a Vue app

2πŸ‘

βœ…

1 year later, Alan’s answer helps me too, but my code failed when calling chart.destroy().

So I searched and found what seems to be the "vue way" of handling it: markRaw, here is an example using options API:

import { markRaw } from 'vue'
// ...
export default {
  // ...
  beforeUnmount () {
    if (this.chart) {
      this.chart.destroy()
    }
  },
  methods: {
    createChart() {  
      const chart = new Chart(this.$refs["chartEl"], {
        // ... your chart data and options
      })
      this.chart = markRaw(chart)
    },
    addData() {
      // ... your update
      this.chart.update()
    },
  },
}

3πŸ‘

This may be a stale post but I just spent several hours wrestling with what seems like the same problem. Perhaps this will help you and/or future people with this issue:

Before assigning the Chart object as an attribute of your Vue component, call Object.seal(...) on it.

Eg:

const chartObj = new Chart(...);
Object.seal(chartObj);
this.chart = chartObj;

This is what worked for me. Vue aggressively mutates attributes of objects under its purview to add reactivity, and as near as I can tell, this prevents the internals of Chart from recognising those objects to retrieve their configurations from its internal mapping when needed. Object.seal prevents this by barring the object from having any new attributes added to it. I’m counting on Chart having added all the attributes it needs at init time – if I notice any weird behaviour from this I’ll update this post.

Leave a comment