How to add/display multiple chart.js line charts, on same page properly?

Viewed 173

From a few weeks(sadly I'm not very experienced with vue and chart.js ), I'm trying to properly display N number of times, component with LineChart and value, for N number of sensors fetched via API, on a single page. The project is on Vue.Js 3 including Chart.js. I'm NOT using any of the VueJs wrappers for charts, only the Chart.js lib itself!

What I've done so far: displaying the components with LineChart and values inside them successfully, N number of times, but... My problem is that, the data for every chart includes data from the other charts, or something like that. Also when I try to update the charts later, same behavior happens. Which is not what I want, every chart, should have only the data for itself...

Her is the chart config on creation (I need them with the same style for now)

const datasets = {
  labels: ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"],
  datasets: [
    {
      // one line only
      data: [0],
      fill: true,
      backgroundColor: ["rgba(20, 120, 60, 0.3)"],
      borderColor: ["rgba(20, 120, 60, 0.9)"],
      borderWidth: 2,
      pointRadius: 0
    }
  ]
}
const chartData = {
  type: "line",
  data: {},     // empty object
  options: {...}
}

Here is the code for the create and update:

   setup(props){
        let cChart = null
        let chart = null
    
        function chartDataUpdate(ch) {
          const chh = ch  //eslint trows error if i not do that here

          chh.data = datasets
          chh.data.datasets[0].data.push(parseInt(props.thermData, 10))
          if (chh.data.datasets[0].data.length > 10) {
            chh.data.datasets[0].data.splice(0, 1)
          }
          chh.update()
          chh.data = {}
        }
    
        function createChart(ctx) {
          const myChart = new Chart(ctx, chartData)
          return myChart
        }
        onMounted(() => {
          cChart = {}
          cChart = document.getElementById(props.id).getContext("2d")
          if (cChart !== null) {
            chart = createChart(cChart)
          }
        })
        watchEffect(() => {
          setInterval(() => {
            if (cChart !== null) {
              chartDataUpdate(chart)
            }
          }, 3000)
          if (typeof props.thermData !== "number") {
            isDataType.value = true
          }
        })
     }

May be the problem is, because I'm using the same datasets object for all or something else. I'm open for any ideas, or solutions. Thank you in advance.

0 Answers
Related