Passing state after .setState() to child component but not showing up in this.props for child component

Viewed 818

How come I am able to print my this.state.email after running componentDidMount() but when I pass the state to a child component I cannot access it in this.props.email of the child component

class HomePage extends React.Component {
  constructor(props, context) {
    super(props, context);
    this.state = {
      isAuthorized: false,
      name: "",
      email: "",
    };
  }

  loadGoogleApi() {
    ...
    this.makeApiCall()
    ...
  }

  makeApiCall() {
    gapi.client.people.people.get({
      'resourceName': 'people/me',
      'personFields': 'names,emailAddresses',
    }).then(resp => {
      this.setState({
        name: resp.result.names[0].givenName,
        email: resp.result.emailAddresses[0].value
      });
    });
  }

  componentDidMount() {
    this.loadGoogleApi();
  }

  render() {
    return(
      <div>
        { !this.state.isAuthorized ? (
          <button onClick={ this.handleAuthClick } id="authorize-button">Login/Signup</button>
        ) : (
          <div>
            <p>{ "Hello, " + this.state.name + "!" }</p>
            <p>{ "Hello, " + this.state.email + "!" }</p>
            <Main email={ this.state.email }/>
          </div>
        ) }
      </div>
    );
  }
}

Main.js component

class Main extends React.Component {
  constructor(props) {
    super(props);
    this.state = {};
    console.log(this.props);  // PRINTS ==> {email: ""}
  }

  render() {
    return (
      <div> Test </div>
    );
  }
}

export default Main;
5 Answers

You can simply refresh state of your child component (Main.js) through componentWillReceiveProps method as follows.

class Main extends React.Component {
  constructor(props) {
    super(props);
    this.state = { data: this.props.dataParentToChild }; // Initial data set
    console.log(this.props);  // PRINTS ==> {email: ""}
  }

  componentWillReceiveProps(nextProps) {
    this.setState({ data: this.nextProps.dataParentToChild }); // Refresh data  
    console.log(this.nextProps);  // PRINTS ==> {email: "updated value"}
  }
  
  render() {
    return (
      <div> Test </div>
    );
  }
}

export default Main;
Related