0đź‘Ť
What is happening is that you are running your code before your request is done, and it results in running your forEach with default values
currentcohortgraphdata:
[{“Monday”:”0″,”Tuesday”:”0″,”Wednesday”:”0″,”Thursday”:”0″,”Friday”:”0″,”Saturday”:”0″,”Sunday”:”0″}],
Simply move ur code inside .then block
axios.get("api/loadCohortAttendancies").then(({data}) => {
this.currentcohortgraphdata = data
this.$Progress.finish();
var result = this.currentcohortgraphdata;
result.forEach(function (e) {
if (e.Monday > 0) {
alert(e.Thursday);
}
});
});
Alternatively, you can use async/await syntax:
methods: {
async loadCohortAttendancies() {
this.$Progress.start();
const { data } = await axios.get("api/loadCohortAttendancies");
this.currentcohortgraphdata = data;
this.$Progress.finish();
const result = this.currentcohortgraphdata;
result.forEach(function (e) {
if (e.Monday > 0) {
alert(e.Thursday);
}
});
}
},
0đź‘Ť
Since JavaScript is asynchronous, your result.forEach
is running before your axios request is done. You can fix this by simply moving that block of code that relies on currentcohortgraphdata
being set, into another .then()
block following the one that sets the data. Like so:
loadCohortAttendancies() {
this.$Progress.start()
axios.get("api/loadCohortAttendancies")
.then({data} => this.currentcohortgraphdata = data)
.then(() => {
this.$Progress.finish();
var result = this.currentcohortgraphdata
result.forEach(e => {
if (e.Monday > 0) {
alert(e.Thursday)
}
})
})
}
0đź‘Ť
When you execute forEach, the axios.get
request method has not been executed yet.
So, change your code and try it like this
loadCohortAttendancies() {
this.$Progress.start();
axios.get("api/loadCohortAttendancies").then(({data}) => {
this.currentcohortgraphdata = data;
this.currentcohortgraphdata.forEach(function (e) {
if (e.Monday > 0) {
alert(e.Thursday);
}
});
this.$Progress.finish();
});
}