Make sure to wait until the fetch function is finished before triggering another action

When I run console.log(this.detaliiMP), it currently returns an empty array. My goal is to wait for the getData() function to retrieve the data and populate the detaliiMP array before logging it to the console.

Check out the demo here

const app = Vue.createApp({
  data() {
    return {
      detaliiMP: []
    }
  },
  methods: {
    getData() {
      fetch("https://random-data-api.com/api/v2/users?size=5")
        .then(res => res.json())
        .then(data => this.detaliiMP = data)
        .catch(err => console.error(err.message))
    },
    showData() {
      this.getData()
      console.log(this.detaliiMP)
    }
  },
})

app.mount('#app')
<script src="https://unpkg.com/vue@3/dist/vue.global.js"></script>

<div id="app">
  <button @click="getData">Get Data</button>

  <button @click="showData">Console LogOut</button>

  <p v-for="item in detaliiMP">{{ item.first_name }}</p>
</div>

I attempted to use async/await but it seems like I made a mistake somewhere because it's not functioning as expected.

Answer №1

Async/await is the key.

const app = Vue.createApp({
  data() {
    return {
      userDetails: []
    }
  },
  methods: {
    async fetchData() {
      await fetch("https://random-data-api.com/api/v2/users?size=5")
        .then(res => res.json())
        .then(data => this.userDetails = data)
        .catch(err => console.error(err.message))
    },
    async displayData() {
      await this.fetchData()
      console.log(this.userDetails)
    }
  },
})

app.mount('#app')
<script src="https://unpkg.com/vue@3/dist/vue.global.js"></script>

<div id="app">
  <button @click="fetchData">Fetch Data</button>

  <button @click="displayData">Display in Console</button>

  <p v-for="item in userDetails">{{ item.first_name }}</p>
</div>

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

How can I export an ES Object in Node.JS to an NPM package?

I am currently facing a challenge involving an ES5 object/function that I want to integrate into an NPM package. This particular object is within a namespace defined as MY_NAMESPACE.myObject = function(){...} where MY_NAMESPACE is simply an object. Typic ...

Troubleshooting: Angular Custom Elements malfunction on Firefox, Microsoft Edge, and Internet Explorer

Experimented with the Angular Elements Demo After downloading, installing, and building the demo locally. Implemented the following code: <!doctype html> <html lang="en> <head> <meta charset="utf-8> <title>Angular Eleme ...

Switching from jQuery to vanilla JavaScript, iterating through each HTML tag in a loop

Here is my current jQuery code that I am looking to convert into vanilla JavaScript. var elements = []; document.querySelectorAll('*:not(script, style, iframe)').forEach(function(element) { elements.push(element); }); I have tried using d ...

Building a Dynamic Web Widget with the Perfect Blend of HTML, JS,

While developing a javascript-based web widget, I am aiming to steer clear of using iframes and avoid relying on the page's CSS. It is infeasible for me to utilize custom CSS, as it defeats the purpose, and iframe integration would not present a user- ...

As the second line of Javascript code is being executed, the first line is still

I have a task where I need to execute a SQL SELECT statement and save the results. Then, those results need to be passed into a function to generate a graph using the data points provided. Refer to the code snippet below for details. var dataKWhr = getCov ...

Generate Sub Menu for Navigation Bar based on Main Menu Selection

I'm currently working on dynamically setting menu items and sub menu items using React Props. My code successfully iterates through the main list items navItems.label and displays them. However, I'm facing an issue with displaying the sub menu i ...

Utilizing jQuery and JSON to showcase the contents of an array

My goal is to display all the items in an array by utilizing JSON and jQuery from the Song of Ice and Fire API. Currently, I am only able to display one item from each of the arrays. If you want to view the codepen, click here: https://codepen.io/frederic ...

Issue encountered during npm install after VueJS project creation

Just recently, I set up VueJS and started a new project. Following the instructions in their installation and quick start guide VueJS Getting Started, here's what I did: > npm init vue@latest > cd (My Project Name Here) > npm install Howe ...

Set a consistent pixel measurement for all images

I am working on a project where I have an image of a card that needs to be repeated 30 times. Each time the card is repeated, I want it to overlap with the previous card in a specific position, resembling a deck of cards. The issue I am facing is that whe ...

Clickable element to change the display length of various lists

I am working on a project where I have lists of checkboxes as filters. Some of these lists are quite long, so I want to be able to toggle them to either a specified length or the full length for better user experience. I have implemented a solution, but th ...

Tips for showcasing req.validationError in a form

I am currently working on validating a sign-up page using node.js/express. My main goal is to show the error messages generated by req.validationErrors() directly on my form. I have opted to use ejs instead of jade, and while I found a solution for display ...

Can you explain the concept of the "one true source"?

After reviewing this particular article, I came across a significant statement in the "Controlled Components" section: The integration of both can be achieved by ensuring that the React state is considered as the “single source of truth”. Can you ...

Using NextJS to navigate user journey by mapping an array of values from Formik to

I really appreciate all the help I've received so far, but I'm facing an issue trying to map an object with an array within it to the router. Here is my current code: const initialValues = { region: query.region || 'all', campt ...

How can we update the form builder or form group in Angular 2 when making changes to the existing data in a table? I'm a bit confused on how to implement router

<tr *ngFor="let row of categories "> <td>{{row.categoryName}}</td> <td>{{row.visible}}</td> <td>{{row.instanceNumber}}</td> <td> <a class="btn btn-info btn-fill " [routerLink]="['/con ...

Switch up the direction of vue-toasted pop-ups with these simple steps

I am utilizing vue-toasted to display notifications. By default, the notification pops down from the top. Here is the code: <v-btn @click="onTest" /> ... onTest() { this.$toast.info('Test!', { containerClass: 'toaste ...

Angular Card Flip Directive and Its Isolated Scope

In my AngularJs project, I am working on a directive to achieve card flipping functionality. Using HTML(Jade) card display | this is sid input.btn.btn-primary(type='submit', value=&apos ...

Downloading Files from Mongodb Using GridFS

I am working on an application that enables users to upload and download various files. Currently, I am facing a challenge where I am able to retrieve the file from my MongoDB database and download it locally on my machine, but I am encountering difficulti ...

Click functionality being incorporated into Material UI

I need assistance with incorporating an onClick event handler in a material ui example, but it doesn't seem to be working as expected. <Tooltip title="Filter list"> <IconButton aria-label="Filter list"> <FilterListIcon/> </ ...

Error in JScript encountered during the downgrade to .NET Framework 2.0

Working on a Web Application project has brought about some challenges for me. Originally created in .NET 3.5, I recently found out that it has to be converted to .NET 2.0 (sigh). This transition not only caused issues with the LINQ functionalities but als ...

Obtaining undefined values for req and resolvedUrl in GetServerSideProps function

In my project, I am currently using next.js version ""next": "^12.1.4"" and node version ""@types/node": "^14.14.6". I have created a function called getServerSideProps with parameters req and resolvedUrl. When the ...