Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Async and await in Vuejs

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?

like image 559
John Nguyen Avatar asked Aug 08 '17 09:08

John Nguyen


1 Answers

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);
    }));
  }
}
like image 64
A1rPun Avatar answered Nov 19 '22 12:11

A1rPun