Undefined Is Not A Function This.setstate
Solution 1:
The problem is with:
.catch(function(error) {
this.setState({ loginButtonPressed: false });
Alert.alert(error.toString());
});
you create an anonymous function where this
will reference this anonymous function (Object), not a React Object.
I see you can use arrow functions, so fix it like:
.catch((error) => {
this.setState({ loginButtonPressed: false });
Alert.alert(error.toString());
});
With arrow function this
will reference context in which it is used.
Solution 2:
Or you can keep a copy of the reference to this, like this:
const self = this; (first line in your function);
and use "self" instead of "this" anywhere in the function.
You can use this in places where you might not be able to use arrow functions.
Solution 3:
You need to bind
to this
in order to have access inside the callback. Try it with the arrow functions.
Solution 4:
Are you extending react component?
If you are not you will need to do that to utilize setState
, if you are you will need to be sure to create the state in a constructor before you update it with setState
elsewhere.
Something along the lines of:
classLoginextendsReact.Component {
constructor(props) {
super(props);
this.state = { loginButtonPressed: false };
this.login = this.login.bind(this);
}
login(email, password, navigate) {
this.setState({ loginButtonPressed: true });
firebase
.auth()
.signInWithEmailAndPassword(email, password)
.then(function(user) {
navigate('Profile');
})
.catch(function(error) {
this.setState({ loginButtonPressed: false });
Alert.alert(error.toString());
});
};
render() {
return (
<ButtononClick={this.logIn}>Login</Button>
);
}
}
Solution 5:
An arrow function remembers it lexical scope. Refer MDN documentation -- "An arrow function does not newly define its own 'this' when it's being executed in the global context; instead, the 'this' value of the enclosing lexical context is used, equivalent to treating this as closure value. Thus, in the following code, the 'this' within the function that is passed to setInterval has the same value as 'this' in the enclosing function:" function Person() { this.age = 0;
setInterval(() => {
this.age++; // |this| properly refers to the person object
}, 1000);
}
var p = newPerson();
Post a Comment for "Undefined Is Not A Function This.setstate"