Use a promise then to handle the response.
I'm not sure how the data is formatted, so you'll likely need additional checking to verify the data is in correct format. You should return the axios promise and handle the returned data using a then handler, and it's a good idea to implement catch too
part1:
import axios from 'axios';
export default {
get(){
return axios.get('/emails') // <--- Need this to return the promise
.then((response) => {
return response.data.data;
}).catch((error) => {
console.log(error);
throw error.response; // <-- use throw to be able to use catch
});
},
update(){
}
}
part 2:
<template>
<div class="col-md-7 pt-5 pr-2 pb-5 pl-5">
{{emails}}
</div>
</template>
<script>
import EmailMessageService from '../../services/EmaiMessageService';
export default {
data(){
return {
pageNumber: 0,
emails:[],
}
},
mounted(){
EmailMessageService.get()
.then(response => {
console.log(response)
this.emails = response
})
.catch(error => {
// handle error
console.error(error)
})
}
}
</script>
response to whether you should always have a catch
TL;DR;
You should always strive to handle exceptions, at every stage.
There are three layers at work here
- View
- Wrapper
- Wraps and abstracts the request library/function
- Axios/Request(er)
- the actual request making and handling library
Your request originates from your View layer, initiated by some click or during mount(), goes to wrapper layer, which abstracts the Axios request. Once the Request is made, and the response is received, it travels back from Axios to the wrapper and then back to your View. Each layer is does some error checking.
The axios response handler can only tell, using headers and parsing of json, whether the data received back was valid, so you should implement additional error validation at your wrapper. You can also add additional logic at this stage that could do a fallback request or notification. But it still needs to tell the view that an error happened. At the view layer your error validation would determine what the user sees or what options they are presented with either on success or on failure; this decision cannot be made by the Wrapper nor Axios, as they are not meant to touch the DOM.
if you do not implement a catch at the View Layer, whether the error comes from the wrapper or axios you will end up with two possible issues during an exception.
You don't know if you're resolving an error or a correct response,
you may never get a then() fired and without a catch, you can have the user waiting without any notification.
So, the way I would handle this, is that the user sees a loading spinner by default, somewhere within the then function, or a call within, the loading spinner would be replaced with the actual data. if I see a catch however, I would use an error message to replace the spinner.
get. Then inmountedyour code will look something like this:EmailMessageService.get().then(emails => this.emails = emails).