Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React use componentWillReceiveProps to re-render the component

Tags:

reactjs

redux

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>
    )
  }
}
like image 290
pbgnz Avatar asked Feb 15 '17 00:02

pbgnz


1 Answers

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>
    )
  }
}
like image 180
finalfreq Avatar answered Oct 23 '22 03:10

finalfreq