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?

1
  • See stackoverflow.com/questions/14220321/… . 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 Commented Sep 3, 2022 at 13:01

1 Answer 1

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>

Sign up to request clarification or add additional context in comments.

2 Comments

That helps, but I am trying to do this in a loop so I guess I need to figure out some other way
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.

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.