Home > Enterprise >  Using promise in Vue, How do i get data from API?
Using promise in Vue, How do i get data from API?

Time:09-30

In my repository.js i have the following:

async getAllContactRequests() {
    return new Promise(() => {
      axios
        .get("http://127.0.0.1:8000/api/contactRequests", {
          headers: { "Authorization": "Bearer "   sessionStorage.getItem("user_token") }
        })
    })
  }

In my Vue component i have:

<script>
import repository from "@/api/repository";

export default {
  name: "posts-index",

  data() {
    return {
      apiData: null,
    };
  },

  async mounted() {
    console.log("This prints");
    this.apiData  = await repository.getAllContactRequests().then(result => result.data);
    console.log("This doesn't print");
  },
};
</script>

I don't get the data from the promise, and every line after the call to the api function does not execute. What am i doing wrong?

CodePudding user response:

Assuming the API returns JSON data, you can refactor the codes above into:

async getAllContactRequests() {
    return axios
        .get("http://127.0.0.1:8000/api/contactRequests", {
          headers: { "Authorization": "Bearer "   sessionStorage.getItem("user_token") }
        })
  }

This is because Axios returns Promise, and there is no need to redundantly wrap it into a Promise.

To consume the response data, you simply await for the API request:

import repository from "@/api/repository";

export default {
  name: "posts-index",

  data() {
    return {
      apiData: null,
    };
  },

  async mounted() {
    const response = await repository.getAllContactRequests()
    if (response && response.data) {
       this.apiData = response.data
    }
  },
};
  • Related