0

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?

Saggy
  • 75
  • 7
  • 2
    The promise is never resolved. Do not return a new Promise, just return `axios.get` because it's a Promise already. You don't even need the `async` at all in that specific case (in the repository) – briosheje Sep 29 '21 at 07:55
  • 1
    [What is the explicit promise construction antipattern and how do I avoid it?](https://stackoverflow.com/questions/23803743/what-is-the-explicit-promise-construction-antipattern-and-how-do-i-avoid-it) – Andreas Sep 29 '21 at 07:57
  • An additional note. When using `await` you in most cases don't need `then`. `this.apiData = await repository.getAllContactRequests().then(result => result.data);` can be written as `this.apiData = (await repository.getAllContactRequests()).data;` – t.niese Sep 29 '21 at 07:57
  • AWESOMe! So far so good. Now, how do i actually access the data? The object is Promise, can i convert it to JSON somehow? or is there a better way? – Saggy Sep 29 '21 at 08:05

1 Answers1

1

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
    }
  },
};
Heri Hehe Setiawan
  • 1,535
  • 1
  • 12
  • 19
  • Should the getAllConectRequests() method have the async keyword if you aren't using await in the body of the function? – Kevin S Jul 25 '22 at 05:08