Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Async/await axios calls with Vue.js

I'm having a little trouble setting one of my this. values within my Vue.js application. I believe I'm either not understanding async axios calls correctly, or how async works within Vue.js.

I have the following three methods:

updateAvailability(availability) {
    if (availability == true) {
        this.showYourDetails();
    } else {
        this.showBookingDetails();
    }
},
checkAvailability: async function(event) {
    event.preventDefault();
    const availability = await this.handleAvailabilityRequest(event);
    this.loading = true;
    console.log(availability); //This evaluates to undefined
    const availabilityUpdate = await this.updateAvailability(availability);
    this.loading = false;
},
handleAvailabilityRequest: async function(event) {
    event.preventDefault();
    let valid = this.validateFieldsForAvailabilityRequest(); //Ignore this for this particular question, assume valid is always true

    if (valid) { // This is true
        let config = {
            headers: {
                "X-CSRFToken": this.csrfToken,
                "Content-Type": 'application/x-www-form-urlencoded',
            }
        }

        let formData = new FormData();
        let reservationTime = this.reservationHourSelected + ':' + this.reservationMinuteSelected;

        formData.set('type', 'availability_request');
        formData.set('session_name', this.sessionName);
        formData.set('reservation_party_size', this.reservationPartySize);
        formData.set('reservation_date', this.reservationDate);
        formData.set('reservation_time', reservationTime);

        await axios.post('{{ request_absolute_uri }}', formData, config).then(function(response) {
            this.availabilityMessage = response.data.message;
        }).catch(function(error) {
            this.availabilityMessage = false;
            console.log(error);
        });
    }
    return this.availabilityMessage;
}

My response.data.message is being passed back from my framework as True/true but it seems I'm not returning anything from the await this.handleAvailabilityRequest() function? The post definitely hits the server as logging shows everything I want - then returns back message = true in json response context.

So, I guess ... help! Completely dumbfounded as to why this isn't working other than it being an issue with waiting for the promise...

like image 848
GCien Avatar asked Jun 15 '18 09:06

GCien


People also ask

Can you use Axios with async await?

To use async and await with Axios in React, we can call axios in an async function. We call axios with the URL we want to make a GET request to. It returns a promise that resolves to an object with the data property set to the response data. So we use await to return the resolved value from the promise.

Does Axios work with Vue?

Axios is a popular JavaScript library used to make HTTP requests. It is a promise-based HTTP client used in JavaScript or with other Javascript libraries like Vue. js or React.

Does Axios request async?

Axios is a promise based HTTP client for the browser and Node. js. Axios makes it easy to send asynchronous HTTP requests to REST endpoints and perform CRUD operations. It can be used in plain JavaScript or with a library such as Vue or React.

How use async await with Axios node JS?

To use the async/await syntax, we need to wrap the axios. get() function call within an async function. We encase the method call with a try... catch block so that we can capture any errors, similar to the catch() method we used in the Promise version.


1 Answers

Why use promises pattern if you are using async await. This removes the use of callbacks and this binding being lost

You can do it like this

handleAvailabilityRequest: async function (event) {
  event.preventDefault();
    ...

  try{
   let response =  await axios.post('{{ request_absolute_uri }}', formData, config)
      this.availabilityMessage = response.data.message;
  }catch(error) {
      this.availabilityMessage = false;
      console.log(error);
    };
  }
  return this.availabilityMessage;
}

You can use try/catch block for handling errors when using async/await

like image 90
Vamsi Krishna Avatar answered Oct 12 '22 02:10

Vamsi Krishna