2👍
✅
this.convs
gets populated when the call to get the data has resolved. So in order to use it you have to wait for that promise to resolve.
To be able to wait on a promise, you have to return
it. So fetchConversation()
needs to return axios.get()
(which is the promise you’ll be waiting on):
methods:{
fetchConversation() {
return axios.get('getConvs').then(response => {
this.convs = response.data;
});
}
}
Now, that fetchConversation()
returns the promise, you have two ways of waiting on it: either make created
async
and use await
:
async created() {
await this.fetchConversation();
console.log(this.convs[0]);
}
or call .then()
method on the promise:
created() {
this.fetchConversation().then(() => {
console.log(this.convs[0]);
})
}
👤tao
1👍
In request success callback extract the first item :
export default
{
data(){
return {
convs_id: null,
convs: [],
}
},
created(){
this.fetchConversation();
},
methods:
{
fetchConversation()
{
axios.get('getConvs').then(response=>{
this.convs = response.data;
let [firstConvs]=this.convs;// es6 syntax of destructing the array
this.convs_id = firstConvs.id;
});
}
}
}
Source:stackexchange.com