In Vue 3, my component "App" makes an asynchronous API request to retrieve info about a "purchase". This "purchase" is passed on to its child component "DeliveryInfo".
In "DeliveryInfo", I need to make another request based on the "customerId" property contained in the "purchase" prop. However, when "DeliveryInfo" receives the "purchase" prop, it's value is at first undefined. The second API request would then fail.
To avoid this, I used a watcher, so that when "DeliveryInfo" eventually gets the content of the "purchase" prop, it would then make a call to the API and update its own data.
I heard this is not good for performance. Could someone help me to improve my code ?
Here's my App.vue component :
<template>
<Purchase :purchase="purchase" />
</template>
<script>
import Purchase from "./components/Purchase"
export default {
name: "App",
components: { Purchase },
data() {
return {
purchase: []
};
},
methods: {
async fetchPurchase(id) {
const response = await fetch(`myapi.com/purchases/${id}`);
const data = await response.json();
return data;
}
},
async created() {
// example with a specific id
this.purchase = await this.fetchPurchase(79886);
}
}
</script>
And my DeliveryInfo component :
<template>
<div class="delivery-info embossed">
<div>
<h4>Adress</h4>
<p>{{ purchase.deliveryAdress }}</p>
<p>{{ purchase.deliveryCity }}</p>
</div>
<div>
<h4>Customer info</h4>
<p>{{ customerData.firstname }} {{customerData.lastname}}</p>
<p>{{ customerData.phone }}</p>
</div>
</div>
</template>
<script>
export default {
name: "DeliveryInfo",
props: ["purchase"],
data(){
return{
customerData: {}
}
},
methods:{
async fetchCustomer(){
if(!this.purchase){
return
}
const response = await fetch(`myapi/customers/${this.purchase.customerId}`)
this.customerData = await response.json()
}
},
watch : {
purchase(){
this.fetchCustomer()
}
}
}
</script>