Within my Vue component, I am attempting to retrieve data from an API using axios.
<template>
<div>
This is Default child component
{{tools[0].name}}
</div>
</template>
<script>
import { CustomJS } from '../js/custom.js';
export default {
name: 'HomeContent',
props: {
tools: []
},
methods: {
fetchData() {
const customJs = new CustomJS();
return customJs.getTools();
}
},
created() {
this.tools = this.fetchData(); //need a way to wait for response here
}
}
</script>
The getTools()
function resides in a separate JS file outside of the Vue component file, which utilizes axios.get to make the API call.
getTools(id = 0){
this.apiTool += (id > 0) ? id : '';
axios.get(this.apiTool, {
})
.then(function (response) {
console.log(response.data);
return response.data;
})
.catch(function (error) {
console.log(error);
});
}
An issue arises where {{tools}}
returns undefined as the getTools()
function takes time to fetch the response data. How can one properly handle waiting for and returning the response data?