Home > front end >  How to return data from fetch to use in template in Vue
How to return data from fetch to use in template in Vue

Time:09-04

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?

CodePudding user response:

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>

  • Related