I have a input that when it changes it should updated its computed counterpart which does an axios request however the computed property is always undefined despite there is a response from the server and I see the data does print out . Its’ just not returned for some reason.
computed: {
itemsChildren() {
if (this.parentReview == null) {
return null
} else {
const formData = new FormData();
formData.append('ID', this.parentReview["ID"]);
axios({
method: 'POST',
url: window.location.origin + '/API/List',
data: formData,
headers: {
'Content-Type': 'multipart/form-data',
"RequestVerificationToken": document.forms[0].querySelector('input[name="__RequestVerificationToken"]').value,
}
}).then(response => {
const res = response.data;
return res;
}).catch(error => {
if (error.response.status == 401 || error.response.status == 402 || error.response.status == 403) {
window.location.href = error.response.headers.expiredtokenredirecturi
}
console.log(error.response);
});
}
}
}
Should computed properties not return API responses?
2
Answers
You are not returning anything from your function, it is a basic mistake when working with Asynchronous code.
Just use async/await for your axios response, also
itemsChildren
should beasync
PS: I am trying to help, but I do not have the expertise in what
computed
is and how it works, or even if async can be used with it.You can read about asynchronous programming here: https://dev.to/raxraj/asynchronous-javascript-from-callbacks-to-asyncawait-a-journey-through-evolution-5578
You are not correctly returning your axios request. You can return the axios request or even better do one of the following. Also I do not think that a 401,402,403 response from the server will trigger an error. But you should verify this, because I am not sure how axios handles those responses.
Using Promises
Using Async/Await