'Make API call before computed properties run Vuejs
I am creating a vuejs application that need to fetch data from the backend using API. And the data will be populated using a computed properties and display it on the screen.
But I found that the computed properties will run before the data is fetched from the backend. This make the computed properties always return me an error. (Data not exists at the time computed properties is running)
Here is the example of my code.
<template>
<!-- Populated data will be display here -->
<div v-for="service in serviceList" :key="service"></div>
</template>
<script>
import { getServices } from "@/services/product.js";
export default {
name: "Services",
data() {
return {
services: null,
};
},
methods: {
async fetchService() {
try {
const response = await getServices();
this.services = response.data;
} catch (error) {
console.log(error);
}
},
},
computed: {
serviceList() {
// services will be populated here
return this.services;
},
},
created() {
// Featch data from backend
this.fetchService();
},
};
</script>
Is there any ways to make my data ready before the computed properties is running?
Thank you.
Solution 1:[1]
Based on the current code snippet there's no need to a computed property, just init the services with an empty array :
data() {
return {
services: [],
};
},
then use it in template :
<div v-for="service in services" :key="service"></div>
You can format the response directly inside try block.
try {
const response = await getServices();
// format your response data here and then bind in the `this.services`
this.services = response.data;
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Rohìt JÃndal |
