Ben Ahlander Ben Ahlander - 1 month ago 9
React JSX Question

react props not updating state

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)
}

Answer Source

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)
});