I am trying to make a form, where users can change their email address of the account. I want them to enter their password to validate them. So I have a function that is doing the email change, but before it calls the validate function. If the return value is true it goes on. If not an error appears. But when testing it with the correct credentials it always goes into the else although i get a valid axios response.
emailChange() {
if (this.validate() == true) {
var data = JSON.stringify({
email: this.email,
});
this.put(data);
} else {
this.error = "Falsches Passwort";
this.snackbar = true;
}
},
validate() {
var data = JSON.stringify({
identifier: this.loggedInUser.email,
password: "123456",
});
var config = {
method: "post",
url: "http://192.168.190.112:1337/api/auth/local",
headers: {
"Content-Type": "application/json",
},
data: data,
};
this.$axios(config)
.then(function (response) {
console.log(JSON.stringify(response.data));
})
.then(function () {
return true;
})
.catch(function (error) {
console.log(error);
});
},
>Solution :
The function return is not returning to validate. Axios is asynchronous and you need either a promise or a callback.
this.$axios(config)
.then(function (response) {
console.log(JSON.stringify(response.data));
})
.then(function () {
return true; // this does not return to validate(). it returns just here
})
.catch(function (error) {
console.log(error);
});
This is a way to implement it.
emailChange() {
this.validate((error, isValid) => {
if (isValid) {
var data = JSON.stringify({
email: this.email,
});
this.put(data);
} else {
this.error = "Falsches Passwort";
this.snackbar = true;
}
})
},
validate(callback) {
var data = JSON.stringify({
identifier: this.loggedInUser.email,
password: "123456",
});
var config = {
method: "post",
url: "http://192.168.190.112:1337/api/auth/local",
headers: {
"Content-Type": "application/json",
},
data: data,
};
this.$axios(config)
.then(function (response) {
console.log(JSON.stringify(response.data));
})
.then(function () {
callback(null, true);
})
.catch(function (error) {
callback(error);
});
}