Reputation: 1740
My API response looks like this
data: {
id: 9,
quantity: 2,
address: "Test Address",
total_price: 144.42,
created_at: "August 07, 2018 04:02:46 AM",
customer: {
id: 3,
name: "Prof. Laurel Lemke",
email: "[email protected]",
role_id: 3,
},
product: {
id: 7,
name: "Pellentesque semper",
description: "raesent sit amet elementum purus.
price: "72.21",
cover_image: "7CPVS7yjqba9iJ7J.jpg",
}
}
And I'm fetching it with axios in which it is trigger when a button is clicked
fetchOrder: function(id){
let vm = this;
axios.get('api/order/' + id)
.then( response => {
vm.order = response.data.data;
vm.orderModal = true;
})
.catch( error => {
console.log(error);
});
},
The response is successful and I'm outputing the value with
<span>{{ order.address }}</span> //Test Address
However, when i tried
<span>{{order.customer.name}}</span>
I'm getting an error of
Cannot read property 'name' of undefined
How can i fix this ? thanks
Upvotes: 0
Views: 935
Reputation: 4743
The issue is that your code is executed but the API call is Async
and so customer is not defined till the time API returns the response but the code is executed. You need to put a check to customer before accessing the value.
order.address
worked because order might be object and so order.address will be undefined till the API response is fetched. However, for order.customer.name, customer is undefined and so customer.name breaks.
Put a check of {{order.customer && order.customer.name}}
and it should work fine
Upvotes: 2
Reputation: 8162
Change it to:
<span>{{order.customer && order.customer.name}}</span>
Upvotes: 1