Seeking to initialize a Chart.js chart with an API, I've come across tutorials that update the data post page rendering. However, I wish to update the chart before the page renders, enabling me to view the initialized chart without any reload.
<template>
<h3>Stacked</h3>
<Chart type="bar" v-if="isReady" :data="stackedData" :options="stackedOptions"/>
</template>
<script>
import axios from "axios";
import {defineComponent, ref} from 'vue';
export default {
data() {
return {
isReady: false,
stackedData: {
labels: ['A', 'B', 'C', 'D'],
datasets: [{
type: 'bar',
label: 'Something',
backgroundColor: '#42A5F5',
data: this.list_all
}, {
type: 'bar',
label: 'Another',
backgroundColor: '#66BB6A',
data: this.list_intersection
}]
},
stackedOptions: {
tooltips: {
mode: 'index',
intersect: false
},
responsive: true,
scales: {
xAxes: [{
stacked: true,
}],
yAxes: [{
stacked: true
}]
}
},
basicOptions: null,
//---------------------------------------------------
all:[],
list_intersection:[],
list_all:[]
}
},
beforeCreate() {
let apiKaderURL = 'http://localhost:4000/apiKader';
axios.get(apiKaderURL).then(res => {
this.all = res.data;
this.saveData()
this.isReady=true;
}).catch(error => {
console.log(error)
});
},
methods:{
saveData: function (){
for (var i in this.all){
if(this.all[i].id==='2' ){
this.list_all.push(this.all[i].someNumber)
}
if(this.all[i].id==='8'){
this.list_intersection.push(this.all[i].someNumber)
}
}
return this.list_all && this.list_intersection
}
}
}
</script>
In essence, I use Axios to fetch values, filter them accordingly, and then assign them back to the data property of the chart objects for initialization purpose.
Despite my efforts by utilizing beforeCreate
, the chart fails to display any values even though I believe I am initializing the values prior to rendering.
I also experimented with using vue-chartjs
, but it seems inadequate for Vue 3 or perhaps I made some error in the process.
Any insights on how I can achieve this would be greatly appreciated. Thank you in advance!