0

My code:

   componentDidMount() {
       this.getEmail;
       console.log("checkpoint")
   }

   getEmail = () => {
       var email="something";
       this.setState({
           email: email,
       });
       console.log(this.state.email)
  }
  render() {
    return (
          <View>
            <Text style={styles.text} onPress={this.getEmail}>email :{this.state.email}</Text>
          </View>
    );
  }

Console.logs :

//nothing happened?
checkpoint
(onPress Text into JSX)
this.state.email
something

So my function works well but ComponentDidMount doesn't execute getEmail, but if i press "email :" this load my state and all is fine.

I would like that ComponentDidMount execute my function

JJJ
  • 32,902
  • 20
  • 89
  • 102

3 Answers3

1
componentDidMount() {
    this.getEmail();
    console.log("checkpoint")
}

Of course, onPress={this.getEmail} is executed when you press the text, but that's because onPress event listener make this.getEmail into this.getEmail()

ZeroCho
  • 1,358
  • 10
  • 23
1

You need to change componentDidMount function:

componentDidMount() {
       this.getEmail();
       console.log("checkpoint")
   }

and tell me if it's what you looking for...

Idan
  • 3,604
  • 1
  • 28
  • 33
0

You need to invoke getEmail:

componentDidMount() {
    this.getEmail();  // () is added here
    console.log("checkpoint")
}

Also, you wrote:

getEmail = () => {
   var email="something";
   this.setState({
       email: email,
   });
   console.log(this.state.email)
}

which is wrong. setState is asynchronous and this.state.email might not be there when you log it (take a look on When to use React setState callback). To fix this you should write:

getEmail = () => {
   var email="something";
   this.setState({
       email: email,
   }, () => console.log(this.state.email));
}
Maor Refaeli
  • 2,417
  • 2
  • 19
  • 33