Utilizing retrieved data from API calls in subsequent Vue 3 methods

Hello, I'm having an issue with using fetched data in a different method within VUE 3. My goal is to load all the data when the app starts and then be able to use it multiple times throughout the code. Here is my current code snippet:

const app = Vue.createApp({
 data() {
  return {
   dataAll : [],
  };
 },

 mounted() {
  this.getData();
  this.otherFunction();
 },

 methods: {
  getData() {
   fetch('app/api.php')
   .then((response) => response.json())
    .then((data) => {
      this.dataAll = data;
      //this.dataAll = JSON.parse(JSON.stringify(data));
    });
  },
  otherFunction() {
   console.log(this.dataAll);
  }
});

However, the console is showing Proxy {} - Array(0). Can anyone point out where I might have made a mistake? Thanks.

Answer №1

The asynchronous nature of the fetch function means that you must ensure the getData function resolves before executing otherFunction.

Make sure to wait for the promise to resolve before calling any other functions that rely on the fetched data:

const app = Vue.createApp({
  data() {
    return {
      allData: [],
    };
  },
  mounted() {
    this.getData().then(() => {
      this.otherFunction();
    })
  },
  methods: {
    getData() {
      return fetch('app/api.php')
        .then((response) => response.json())
        .then((data) => {
          this.allData = data;
        });
    },
    otherFunction() {
      console.log(this.allData);
    }
  }
});

You can also utilize async await for a cleaner approach:

const app = Vue.createApp({
  data() {
    return {
      allData: [],
    };
  },
  async mounted() {
    await this.getData();
    this.otherFunction();
  },
  methods: {
    async getData() {
      const data = await fetch(
        "app/api.php"
      ).then((response) => response.json());
      this.allData = data;
    },
    otherFunction() {
      console.log(this.allData);
    }
  }
});

Learn more about using the fetch API here

Discover how async and await can simplify your code

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

Implementing Angular2 with conditional loading

One of the requirements for my project is to redirect users to the login page before loading the Angular2 application, without actually loading it. The project is built using angular2-quicksart. After minifying the Angular2 js file: <script> va ...

"Enhance your website with the magic of jQuery magnific-popup

Is there a way to add an additional button to the jquery magnific-popup component that can close the dialog box? I am currently utilizing this component to insert descriptions for photos, so I need a submit button that will successfully add the descriptio ...

JavaScript and Angular are being utilized, incorporating code from various .ts files

Currently, I am working on a project with Angular4. I have successfully created a filter in my app.component.ts which is functioning well in my app.component.html. <button (click)="filterBy('cars')">Cars</button> Even though the fil ...

Retrieving a date and time value from an object based on a specific range

Having trouble displaying all the user IDs and creation dates within a specific date range in a table. I'm struggling with filtering the data based on dates. Can someone help me identify what I might be doing wrong? I've attempted to replicate th ...

What is the best way to show an array within a string using javascript?

Take a look at this code snippet : const names = ["Alex", "John", "Kit", "Lenny"]; for(let i = 0; i < 4; i++) { $("body").append("<p>" + names[i] + "</p>'); }; Can you figure out how to dynamically add each item in the 'names&a ...

Axio GET request in VueJS does not return a response body when using Amazon API Gateway

UPDATE: While Postman and browsers are able to receive valid response bodies from an Amazon API Gateway endpoint, other web applications are not. This is a basic GET request with no headers, and no authentication is needed for the API endpoint. The data is ...

challenges encountered with the clearTimeout() method in vue.js

I am currently working on implementing a shopping cart using Vue, but I am encountering some challenges. As I am new to using this library, it is possible that I am making some basic mistakes. Here is the issue I am facing: When I add an item to the cart, ...

What is the process to obtain the child theme URL in WordPress?

Currently, I am working on creating a child theme for my WordPress website. I have successfully uploaded the assets folder which contains both CSS and JavaScript files. This child theme will be completely customized to suit my needs. Within the <head&g ...

Vue.js transition-group does not apply the *-move class

As I dive into learning Vue, I find myself wondering if I may have overlooked something fundamental or stumbled upon a bug. Despite multiple readings of the documentation at https://v2.vuejs.org/v2/guide/transitions.html#List-Move-Transitions, I still can& ...

Achieving uniform card height and positioning the shop button at the bottom of each card

https://i.sstatic.net/2i7hc.png The first card in the image above has a stretched height due to its long title, causing the second card's height to also stretch. However, the shop button is not placed at the bottom. I aim to position the button at t ...

Is your Vue.js chart malfunctioning?

I have been experimenting with chart.js and vue.js. The component I created is called MessageGraph, and it is structured like this (with data extracted from the documentation): <template> <canvas id="myChart" width="400" height="400">< ...

Display a visual progress indicator during audio recording

I am currently using the MediaRecorder functionality to capture audio and I would like to display a progress bar showing the recording process. Here is the code snippet from my recorder template: <p id="countdowntimer">Current Status: Beginning in& ...

Transferring the value of my PHP variable to a JavaScript file

Hello everyone, <script src="../../record/recordmp3.js?id=<?php echo $_GET['id'];?>&&test_no=<?php echo $_GET['test_no'];?>"></script> <script type="text/javascript" data-my_var_1="some_val_1" data-m ...

Tips for creating a promise in JavaScript that will only return data once an AJAX request has been completed

I'm having trouble getting a updated list to return after making an AJAX call. class ep_List { constructor() { this.urlForAjax = ''; this.dataList = []; this.dataJson = ''; this.dataParams = {}; this.cardLis ...

"Upon loading an FBX file in Threejs, some model parts are not displayed

Hello, I am in need of assistance. I am currently working on importing FBX models into Threejs and here is the import code that I am using: let loader = new FBXLoader(); loader.load(model.obj_path, object => { let mix = new THREE.AnimationMixer(objec ...

Having difficulty choosing an element with protractor's virtual repeat functionality

Initially, I successfully used ng-repeat to select an element. However, the developers have since implemented virtual repeat which has caused the following code to stop working: expect(stores.listStores(0).getText()).toContain('Prahran'); expect ...

How to troubleshoot Django's Jquery datatable aoData not functioning issue

Getting Started with Datatable Initial Data Setup object_list=[{'username': u'Paul', 'phone_number': u'9910087044', 'user_group__name': '', 'manager_name': ' ', 'role&ap ...

Tips for breaking up array elements across multiple "tr" tags

In this particular example, I have a Fiddle set up with multiple tr elements displayed within an ng-repeat. My goal is to have three td elements per row. Would it be necessary to use an inner angularjs ng-repeat and split the iconDets array for this purpos ...

Storing the retrieved JSON data in a variable

My current dilemma involves attempting to store JSON data in a variable, but I'm clearly missing something crucial. Initially, I successfully see the JSON displayed in the console as desired. However, upon subsequent attempts to access it later on, al ...

Just a simple canvas animation

My canvas animation consists of two rectangles moving in different directions, but I believe it can be simplified further. http://jsfiddle.net/tmyie/R5wx8/6/ var canvas = document.getElementById('canvas'), c = canvas.getContext('2d&apo ...