pbgnz
pbgnz

Reputation: 497

React use componentWillReceiveProps to re-render the component

I can't figure out how to make my componenet re-render when the value of this.props.user changes. Initially the value of this.props.user is null but it changes to an actual value seconds after. Below I am showing the child component. The parent component maps the store state to it's props and I pass it to the child component class below.

export class UserInfoComponent extends Component {
  constructor(props){
    super(props);
    this.state = {user: this.props.user}
  }

  componentWillReceiveProps(){
    this.setState({user: this.props.user})
  }

  render() {
    if(this.state.user)
    return (
      <h1>{this.state.user.firstName}</h1>
    );

    return (
      <h1>loading</h1>
    )
  }
}

Upvotes: 14

Views: 24729

Answers (1)

finalfreq
finalfreq

Reputation: 6980

componentWillReceiveProps receives nextProps as an argument. with the code you presently have you are just setting user back to its current state. You need to use the nextProps argument provided.

export class UserInfoComponent extends Component {
  constructor(props){
    super(props);
    this.state = {user: this.props.user}
  }

  componentWillReceiveProps(nextProps){
    this.setState({user: nextProps.user})
  }

  render() {
    if(this.state.user)
    return (
      <h1>{this.state.user.firstName}</h1>
    );

    return (
      <h1>loading</h1>
    )
  }
}

Upvotes: 32

Related Questions