1

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 ?

1
  • 2
    Because when the component is first rendered, this.mail is undefined. And since you aren't calling setState() / using this.state like you're supposed to, render() isn't called again. Either make mail part of the component's state, or force a re-rendering. Commented May 30, 2018 at 13:52

1 Answer 1

3

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;
Sign up to request clarification or add additional context in comments.

3 Comments

either change the state variable to mail or use data instead of mail in render and set state of componentDidMount
yeah, fixed my typo sorry.
Worked ! Thanks mates.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.