1

If I have a function that looks like this:

const loadDescription = async (id: string) => {
    var data = await fetch(`${import.meta.env.VITE_API_BASE_URL}/api/l/${id}`).then(res => res.json()).then((repos) => {
        // console.log(repos);
        return repos.description;
    });
    console.log(data)
    return data;
}

And this correctly prints the data I want, how can I return the data and use it in my template?

I tried like this:

<p>{{  loadDescription(launch._id).then((data) => {
    data
    })
}}</p>

And also this:

<p>{{  loadDescription(launch._id)}}</p>

But this just shows "[object Promise]" in the Vue template.

What am I doing wrong?

mastercooler6
  • 377
  • 2
  • 16
  • See https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call . You can't call it in a template, and this would be harmful because a function is called on each view update. Call it in setup – Estus Flask Sep 03 '22 at 13:01

1 Answers1

2

Templates in vue are data driven, they receive the data from props defined in the <script> part.

So you should use either an computed or data prop.

Pseudo code:

<template>
  <div v-if="description">{{ description }}</div>
  <div v-else>Loading...</div>
</template>

<script>
export default {
  data() {
    return {
      description: null
    }
  },
  mounted() {
    this.description = this.loadDesciption(1)
  },
  methods: {
    async loadDescription(id) {
       const res = await fetch(`${import.meta.env.VITE_API_BASE_URL}/api/l/${id}`)
       const description = await res.json()
       return description
    } 
  }
}
</script>

S.Visser
  • 4,645
  • 1
  • 22
  • 43
  • That helps, but I am trying to do this in a loop so I guess I need to figure out some other way – mastercooler6 Sep 03 '22 at 13:54
  • this.loadDescription() will return a promise. How do you handle that. I have seen in other examples that the global variable is set within the method itself instead of returning which worked for me. – subz Dec 08 '22 at 18:33