3

I would like to use a method to make an API call in a v-for loop, the purpose is to load an object based on a UID.

My method looks like this:

methods: {
  async getTodo(uid) {
  const data = await axios.get(
    "https://jsonplaceholder.typicode.com/todos/" + uid
  );
  return data;
}

}

From my understanding you can include methods inline as such:

{{ getTodo(2) }}

However this always returns [object Promise]

I must have misunderstand the use of methods for this purpose, or the async call in the method itself is incorrect — if anyone can clarify what is wrong here.

1
  • Its a promise - pass value to data instead return Commented Jun 14, 2019 at 17:02

1 Answer 1

1

You can store the asynchronous response in a reactive array when the promise returns. Since it's reactive, the promise response will automatically be displayed once each promise return.

Do something like:

export default {
  data: {
    asyncDataHolder: []
  },
  methods: {
    async getTodo(uid) {
    const data = await axios.get(
      "https://jsonplaceholder.typicode.com/todos/" + uid
    );
    let index = asyncDataHolder.length + 1;
    asyncDataHolder.$set(index, data);
}

And inside your v-for loop:

{{asyncDataHolder[i]}}
Sign up to request clarification or add additional context in comments.

2 Comments

I would never say The ideal logic to do such a thing. There are plenty of other solutions pretty clean to obtain this result. Moreover, the given solution has huge drawback: if the user stays long enough on this page, it will explode memory since your index has no link with uid. You could at least store your data within an object rather than an array. Another drawback is that you never call the getTodo method. I'd do this within the mounted hook.
Ok, you're right. I've updated the answer. About the mounted hook, it's not clear to methe entire flow... That's why I've focused in just giving him an option that works. Upvote for your note.

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.