[Chartjs]-How To Use Api Data With Vue Chart.js

0👍

Have you checked out the examples in the docs?
https://vue-chartjs.org/guide/#chart-with-api-data

Your problem is, that your data api call is async. So your chart is rendered, even if your data is not fully loaded.

There is also an example with vuex which is a bit outdated https://github.com/apertureless/vue-chartjs-vuex

You have to make sure that your data is fully loaded before you render your chart.

0👍

I faced similar issue while implementing Charts with API data in one of my Vue JS apps I was working on. I am using Vuex for state management, a simple solution for this problem is to move "chartData" from "data" to "computed" which would make it reactive. Below is the sample code from my app.

<template>  
    <line-chart v-if="chartData"
      style="height: 100%"
      chart-id="big-line-chart"
      :chart-data="chartData"
      :extra-options="extraOptions"
    >
    </line-chart>
</template>
<script>
import { mapActions, mapGetters } from 'vuex';
import * as expenseTypes from '../../store/modules/expense/expense-types';
import * as chartConfig from "../../components/reports/chart.config";
import BarChart from "../../components/reports/BarChart";

export default {
  components: {
    BarChart,
  },
  data () {
    return {
      extraOptions: chartConfig.chartOptionsMain
    }
  },
  computed: {
    ...mapGetters({
      allExpenses: expenseTypes.GET_ALL_EXPENSES,
      expenseCount: expenseTypes.GET_EXPENSE_COUNT,
    }),
    expenseAmount() {
      let expenseAmount = [];
      this.allExpenses.map((item) => {
        expenseAmount.push(item.amount);
      })
      return expenseAmount;
    },
    expenseLabels() {
      let expenseLabels = [];
      this.allExpenses.map((item) => {
        expenseLabels.push(item.note);
      })
      return expenseLabels;
    },
    chartData() {
      return {
        datasets: [
          {
            data: this.expenseAmount
          },
        ],
        labels: this.expenseLabels
      }
    }
  },
  async mounted() {
    await this.getAllExpenses();
    await this.fillChartData();
  },
  methods: {
    ...mapActions({
      getAllExpenses: expenseTypes.GET_ALL_EXPENSES_ACTION,
    }),
  },
};
</script>

Leave a comment