I have run in to an issue where mounted
will not run the function provided. I have just populated the array to illustrate it's structure. In practice it receives all it's data from the created
instance which connects to the back end.
new Vue({
el: '#app',
data() {
return {
products: [{
"_id": "150",
"name": "Milk",
"description": "Skimmed",
"price": "10",
"ratings": [{
"email": "xyz@mail.com",
"rating": "5"
},
{
"email": "abc@mail.com",
"rating": "3"
},
{
"email": "def@mail.com",
"rating": "1"
},
]
}]
}
},
created() {
fetch('http://localhost:3000/api/products')
.then(res => res.json())
.then(json => this.products = json)
},
mounted() {
// mapping each item of products to merge averageRating calculated
this.products = this.products.map(product => {
// ratings summation
const totalRatings = product.ratings.reduce((acc, {
rating
}) => acc += Number(rating), 0)
const averageRating = totalRatings / product.ratings.length
// returning the merge of the current product with averageRating
return {
...product,
averageRating
}
})
}
})
created
receives all the products without a problem. The issue is that the mounted
instance should calculate the average of all product ratings and store it in this.products
. I use name: {{product.name}}, averageRating: {{ product.averageRating }
to display the product and it's ranking on HTML.
But this does not happen. It's almost as if it skips the mounted
bit. Oddly this works just fine when I call it with <button @click.prevent="getAverage()">
methods : {
getAverage() {
this.products = this.products.map(product => {
const totalRatings = product.ratings.reduce((acc, {
rating
}) => acc += Number(rating), 0)
const averageRating = totalRatings / product.ratings.length
return {
...product,
averageRating
}
})
}
})
I don't know what could be wrong. There are no errors. I have tried chaining it to the .then()
in the created
instance. I need this function to run automatically without having to press a button. I have also tried using various other lifecycle hooks such as beforeMount
.
I have also tried
mounted() {
this.getAverage()
}
Any help will be highly appreciated. Thanks in advance.