Async/await axios calls with Vue.js
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
The problem is here:
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);});
Because you're using a full-fledged function
, your this
inside the .then
does not refer to the instantiated object. Use an arrow function instead so that the this
is inherited from the outer scope:
await axios.post('{{ request_absolute_uri }}', formData, config).then((response) => { this.availabilityMessage = response.data.message;}).catch((error) => { this.availabilityMessage = false; console.log(error);});