Using Vue.js to execute an asynchronous function directly in the code

I am attempting to utilize a method within a v-for loop to make an API call and load an object based on a UID.

Below is the structure of my method:

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

I thought I could simply include the method inline like this:

{{ getTodo(2) }}

However, all it returns is [object Promise]. I must have misunderstood either the use of methods in this context or the implementation of the async call within the method. If anyone can provide clarification on what might be going wrong here, it would be greatly appreciated.

Answer №1

One way to manage asynchronous responses is by storing them in a dynamic array that updates whenever a promise resolves. This allows the response data to be automatically displayed as soon as it's available.

To implement this, you can utilize the following approach:

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);
}

In your template where you have a v-for loop, you can access the stored asynchronous data like this:

{{asyncDataHolder[i]}}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What should you do when you need to send a message from a website to an MQTT broker that lacks Websockets support?

Currently venturing into the realm of web development, I find myself tackling a project that involves sending messages from my website to Thingstream, an MQTT broker. My initial attempt using the MQTT Paho JavaScript library was thwarted by the fact that ...

Avoid accidental overwrites in localStorage using JavaScript

I've been working on a Vue project where I'm implementing a shopping cart feature. In this setup, when the user clicks on a button, the item details are stored in localStorage and then displayed in the shopping cart interface. However, I encount ...

Is there a way to effortlessly upload numerous files in one go when browsing with jquery or JavaScript?

Currently working on a web application and looking to enable multiple file upload functionality within a single browse session, as opposed to selecting one file at a time. The goal is for users to be able to easily select multiple files with just one clic ...

Anticipated outcome for absent callbacks in module API implementation

I am seeking advice on the expected behavior when developing a Node module API. It is becoming complicated in my module implementation to check if the caller has provided a callback before calling it. I am starting to believe that it may be the user's ...

Click event on Angular leaflet marker

Currently, I am using leaflet in conjunction with Angular and have a query regarding making a button clickable within a message popup. Although I understand that I need to compile the HTML, I am struggling to implement it successfully as there are no examp ...

A stylish method for converting CSV data into XML format using Node.js and Express

I am in search of a sophisticated solution to convert CSV files into hierarchical XML format based on a specific template within a Node/Express server. For example, if the CSV is of Type Template "Location": Name,Lat,Lon,Timezone name,lat,lon,timezone it ...

Something is amiss with the PHP email validation functionality

I have been facing issues with the functionality of my form that uses radio buttons to display textboxes. I implemented a PHP script for email validation and redirection upon completion, but it doesn't seem to be functioning correctly. The error messa ...

Unable to trigger submission in jQuery validate function after validation check

I'm currently facing an issue with my form validation using the jQuery validate plugin. Although I have successfully implemented validation for the desired areas of the form, I am unable to submit the form even after filling in all the required input ...

Accessing object properties in the data of a Vue component

Recently delving into Vue, I've run into a bit of confusion. My app connects to a JSON Api using usePage(). The usePage() function allows me to utilize the "page" object within the <template> tag like so: <p>This product costs {{page.pric ...

Ways to implement form validation with JavaScript

I'm currently working on a project for my digital class and I'm facing an issue with my booking form. I have two functions that need to execute when a button is clicked - one function validates the form to ensure all necessary fields are filled o ...

Unknown Parameters Issue with Vue.js Router Links

Within my Vue.js project, I am utilizing params in my navigation.vue component to pass data onto the next page for dynamic routing purposes. Below is an example of how I am using this: <router-link tag="p" :to="{name: 'Main', ...

The distinction between client-side and server-side onclick events

I am working on enhancing a composite control's client side functionality by recreating all methods in JavaScript. However, I am facing some issues: Is it possible to trigger the onclick event on the client side instead of the server side? The state ...

Updating a model within an ng-repeat directive from external sources

Within my controller, there is a repeater where each item has its own unique status: <div ng-controller="..."> <div ng-repeat"...">{{status}}</div> </div> Currently, changing the status within the repeater by using status = &apo ...

Customizing Material-ui picker: concealing text field and triggering modal with a button click

I'm currently working with version 3.2.6 of the material-ui pickers library to develop a component that has different renderings for mobile and desktop devices. For desktop, I have set up a standard inline datepicker with a text input field, while fo ...

The TypeScript error reads: "An element is implicitly assigned the 'any' type because an expression of type 'any' cannot be used to index a specific type."

[Hey there!][1] Encountering this TypeScript error message: { "Element implicitly has an 'any' type because expression of type 'any' can't be used to index type '{ 0: { image: string; title: string; text: string; }; 1: { ...

Generating hierarchical structures from div elements

Looking for guidance on how to parse a HTML page like the one below and create a hierarchical Javascript object or JSON. Any assistance would be much appreciated. <div class="t"> <div> <div class="c"> <input t ...

What methods can be used to monitor changes made to thumbnails on the YouTube platform?

I have embarked on a project to create a Chrome extension that alters the information displayed on the thumbnails of YouTube's recommended videos. In this case, I am looking to replace the video length with the name of the channel. Imagine you are on ...

changing unique characters in JavaScript document

I am currently utilizing DocXTemplater to export a table to a Word document. Within the JavaScript file, there is a module containing special characters that CRM does not permit when creating a file. I attempted to remove the variables with special charac ...

The state of the UI is not updating to reflect the selected item in React Native

I'm working on a component that needs to display all ingredients from my database, but I'm encountering issues with the state not updating as expected. Here are the variables: const image = require('../../assets/backgroundMeal.png'); ...