0

The problem is that state is staying undefined. The first console log of nextProps.userid is showing the correct userid but it is not changing state and the second console log comes back null.

class Profile extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      user: this.props.userid,
    };
  }

  componentWillReceiveProps(nextProps){
    console.log('PROFILE USERID', nextProps.userid)
    const userid = nextProps.userid
    this.setState({user:userid})
    console.log('PROFILE USERID 2', this.state.user)
  }
Ben Ahlander
  • 1,113
  • 11
  • 12

1 Answers1

0

setState is asynchronous. So you cannot expect the value of state to be changed immediately after setState. If you log your state right after the setState then it will show you previous state. If you want to see the updated value of state then try passing a callback to setState like this

this.setState({user:userid}, () => {
    console.log('PROFILE USERID 2', this.state.user)
});
Prakash Sharma
  • 15,542
  • 6
  • 30
  • 37