Reputation: 1316
I am developing a react native app. When I try to execute the following code I got an error. But setStates on other parts of the same file are working fine.
undefined is not a function(evaluating'this.setState({firebaseMessages: "Wrong password"})
.catch(function(error) {
var errorCode = error.code;
var errorMessage = error.message;
if (errorCode === "auth/wrong-password") {
//alert("Wrong password.");
this.setState({ firebaseMessages: "Wrong password" });
this.setState({ isModalVisibleFirebase: true });
this.setState({ loading: false })
return;
} else {
alert(errorMessage);
return;
}
console.log(error);
}
Upvotes: 1
Views: 62
Reputation: 20755
Simple solution is, assign this
to some variable and then use that variable to call setState
.
const _this = this; //write this before fetch method
and then use like this,
_this.setState({ firebaseMessages: "Wrong password" });
Upvotes: 1
Reputation: 157
if you use ES5 way of function define your this
scope will change, use arrow syntax to persist this
scope.
So now you should do .catch((error) => {
instead .catch(function (error){
.catch((error) => {
var errorCode = error.code;
var errorMessage = error.message;
if (errorCode === "auth/wrong-password") {
//alert("Wrong password.");
this.setState({ firebaseMessages: "Wrong password" });
this.setState({ isModalVisibleFirebase: true });
this.setState({ loading: false })
return;
} else {
alert(errorMessage);
return;
}
console.log(error);
}
Upvotes: 1
Reputation: 2220
You likely need to bind your callback function, try this:
catch(function(error) {
var errorCode = error.code;
var errorMessage = error.message;
if (errorCode === "auth/wrong-password") {
//alert("Wrong password.");
this.setState({ firebaseMessages: "Wrong password" });
this.setState({ isModalVisibleFirebase: true });
this.setState({ loading: false })
return;
} else {
alert(errorMessage);
return;
}
console.log(error);
}.bind(this)) // change this line
Alternatively, you can use an ES6 arrow function, like this:
catch((error) => { // change this line
var errorCode = error.code;
var errorMessage = error.message;
if (errorCode === "auth/wrong-password") {
//alert("Wrong password.");
this.setState({ firebaseMessages: "Wrong password" });
this.setState({ isModalVisibleFirebase: true });
this.setState({ loading: false })
return;
} else {
alert(errorMessage);
return;
}
console.log(error);
})
Upvotes: 1