[Vuejs]-VUE 3 – use fetched data in other method

0👍

The fetch function is asynchronous and you are not waiting for the getData function to resolve before calling otherFunction.

Wait for the promise to resolve before calling other functions that depends on the data:

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

Or you can also use async await

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

https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Asynchronous/Promises#using_the_fetch_api

https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Asynchronous/Promises#async_and_await

Leave a comment