1

I'd like to use the value returned from a function called inside my template.

template:

<div class="director">
    {{ fetchDirector(movie.imdbId) }}
</div>

vue.js:

async fetchDirector(movieId) {
    try {
        await axios.post(`http://www.omdbapi.com/?i=${movieId}&apikey=...`)
        .then((res) => {
            return ( res.data.Director )
        })
     } catch(err) {
        console.log(err);
     }
}

I can't figure out how to display the [object Promise] value fetchDirector(movie.imdbId) gives.. Thank you!

2
  • 1
    you can fetch the director on vuejs mounted, and store the director in the data? Commented Nov 6, 2019 at 21:42
  • I need to get a different director for many different elements Commented Nov 7, 2019 at 9:06

1 Answer 1

1
.then((res) => {
  return ( res.data.Director )
})

This arrow function in your example returns the value, but it has no effect on anything. Instead of returning from this function, define a data property on your component, (named for example director), and then, instead of returning from this arrow function, assign the fetched value to the data property like this:

data () {
  return {
    director: ''
  }
},
mounted () {
  axios.post(`http://www.omdbapi.com/?i=${movieId}&apikey=...`)
    .then(res) => {
      this.director = res.data.Director;
    })
}

And render the value in your template:

<div class="director">
  {{ director }}
</div>
Sign up to request clarification or add additional context in comments.

3 Comments

It seems great but I need to use movieId as I am fetching for several elements that need their own director name. How can I do it?
I do not have lot of time at the moment, but could you make the children components themselves handle the fetch? This way you would just move the mounted() hook to the children themselves, and set the data property in them directly.
@Wizzardzz have you tried what I suggested ? How did it go ?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.