I have trouble retrieving data from a REST-API using VueJS, axios, Async/Await with Promise(??). I need to call two different REST-APIs. One is giving me a list and I can iterate through it, which is fine.
<template>
<div>
<div v-if="posts && posts.length">
<div v-for="post of posts">
{{post.name}}
<img :src="getUserPicturePath(post.name)" />
</div>
</div>
</div>
</template>
The other, as you can see, in between the v-for, is calling a method which is using axios.
<script>
import axios from 'axios'
export default {
data: () => {
posts: []
}
created() {
// a method to fill up the post-array
},
methods: {
async getUserPicturePath(name){
const response = await axios.get('linkToApi'+name)
console.dir(response.data.profilePicture.path)
return response.data.profilePicture.path
}
}
}
</script>
The console.dir(response.data.profilePicture.path)
- Part is giving the correct Path to the profilePicture, but the <img :src="getUserPicturePath(post.name)" />
above in the <template>
, writes [Object Promise]
.
Any suggestion how I can get the path?
Vue can't resolve promises in properties so you have to do something like this.
Template
<div v-for="post of posts">
...
<img :src="post.profilePicture" />
...
JavaScript
export default {
created() {
this.posts = ...
await Promise.all(this.posts.map(async post => {
post.profilePicture = await this.getUserPicturePath(post.name);
}));
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With