1

I am getting an error "undefined is not an object(evaluating "this.state.user") while calling login function through a button. the value of this.state.user is from use of onchangeText method. please help. the function is inside a firebase value event.

constructor(props) {
    super(props);
    this.state = { user: '', password: '' };
}

login = () => {
    db.ref('admins/').once('value', function(snapshot) {
        var user = snapshot.child('user_1').val();
        if (this.state.user == user) {
            this.props.navigation.navigate('FACULTYUI');
        }
    });
};
Yohan K
  • 23
  • 4
  • can you add async to the function login login =async () => { } – Ajith Nov 18 '19 at 08:33
  • can you check if you are getting this.state.user inside the `function(snapshot) {console.log(this.state.user)}` if not then please do var self = this; and check for `function(snapshot) {console.log(self.state.user)}`. Let mo know if you have further queries – Shashank Malviya Nov 18 '19 at 08:45

1 Answers1

1

Change this:

db.ref('admins/').once('value', function(snapshot) {

into this:

db.ref('admins/').once('value', ((snapshot) => {

Use the arrow function which uses the lexical scope, which means that the variable defined outside the function will be the same inside also.

from the docs:

An arrow function does not have its own this. The this value of the enclosing lexical scope is used; arrow functions follow the normal variable lookup rules. So while searching for this which is not present in current scope, an arrow function ends up finding the this from its enclosing scope.

Peter Haddad
  • 65,099
  • 21
  • 108
  • 107