7

How can I populate my chart with the data from my API

<script>
import VueCharts from 'vue-chartjs'
import { Pie, Bar } from 'vue-chartjs'
import axios from 'axios'

export default {
data() {
  return {
    dailyLabels: [] ,
    dailyData: []
  }
},
extends: Bar,
mounted() {
  // Overwriting base render method with actual data.
  this.renderChart({
    labels: ['Monday', 'Tuesday', 'Wednesday', 'Thursday ', 'Friday', 'Saturday', 'Sunday'],
    datasets: [
      {
        label: 'Daily Students',
        backgroundColor: '#f87979',
        data: [12, 20, 1, 50, 10, 40, 18]
      }
    ]
  })
},
created() {
  axios.get(`https://localhost:44379/api/DailyStudents`)
    .then(response => {
      // JSON responses are automatically parsed.
      this.dailyData = response.data.days
    })
    .catch(e => {
      this.errors.push(e)
    })
}
}
</script>

MY Api returns This:

[
  {"day":"Wednesday","totalStudents":"21"},
  {"day":"Tuesday","totalStudents":"2"},
  {"day":"Thursday","totalStudents":"20"},
  {"day":"Friday","totalStudents":"23"}
]

Days should be my Label and totalStudents my data

the chart should show of course the number of students by day, but the examples that I found are a little bit confusing.

1 Answer 1

4

You can use Array.map to extract necessary data.

<script>
import VueCharts from 'vue-chartjs'
import { Pie, Bar, mixins } from 'vue-chartjs'
import axios from 'axios'

export default {
  mixins: [mixins.reactiveData],
  data() {
    return {
      chartData: ''
    }
  },
  extends: Bar,
  mounted() {
    this.renderChart(this.chartData)
  },
  created() {
    axios.get(`https://localhost:44379/api/DailyStudents`)
      .then(response => {
        // JSON responses are automatically parsed.
        const responseData = response.data
        this.chartData = {
          labels: responseData.map(item => item.day),
          datasets: [
            label: 'Daily Students',
             backgroundColor: '#f87979',
             data: responseData.map(item => item.totalStudents)
          ]
        }
      })
      .catch(e => {
        this.errors.push(e)
      })
  }
}
</script>

Note that you need to use mixins.reactiveData to make component reactive with data change.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.