Search code examples
javascriptconsole.logreact-state-management

console cannot log state


Trying to log information from state to console returns the error 'undefined is not an object (evaluating 'this.state.userName')'

I am very new to JS and so I really dont know how this works or how it's supposed to work

I tried replacing 'this.state.userName' with

 - (userName) => this.getState(userName)
 - this.state[userName]
 - 'this.state[1]

None of these had the desired effect

Here is my code:

  constructor(props){
    super(props);
    this.state = {
      userName:'User Name',
      userEmail:'',
      loggedIn: false,
    };
  }

  login() {
    console.log(this.state.userName);
  };

I simply want the console to log whatever is assigned to userName, namely 'User Name'

login is called through: onPress={this.login}


Solution

  • Solution found (26/06/19):

    onPress={this.login.bind(this)} or onPress={() => this.login()}
    

    Found by: Chris G