WaLinke
WaLinke

Reputation: 778

Access this variable in render method [REACT NATIVE]

I'm facing an issue trying to render a class variable.

import Api from '../services/Api';
class Boxify extends Component {
  constructor(props) {
    super(props);
  }
  async componentWillMount() {
    this.response = await Api.getUserCurrent();
    this.mail = this.response.data.email;
    alert(this.mail);
  }
  render() {
    return (
      <View>
        <Text>
          {this.mail}
        </Text>
      </View>
    )
  }
}
export default Boxify;

What I can't figure out is why does the alert in the componentWillMount shows me the email_adress, and the render doesn't show anything ?

Upvotes: 1

Views: 1932

Answers (1)

Bruno Mazzardo
Bruno Mazzardo

Reputation: 1586

Try using state instead of a local variable, so the component will render again

import Api from '../services/Api';
class Boxify extends Component {
  constructor(props) {
    super(props);
    this.state = {
     mail : ''
   }
  }
  async componentDidMount() {
    this.response = await Api.getUserCurrent();
    this.setState({
         mail : this.response.data.email;
     })
  }
  render() {
    return (
      <View>
        <Text>
          {this.state.mail}
        </Text>
      </View>
    )
  }
}
export default Boxify;

Upvotes: 3

Related Questions