I'm trying to access the this.state.timeRemaining value from within the componentWillMount() function. I've destructured the this.state object and renamed the value to "swag". I expect my console.log() statement to print out "5" (as I have set the state and run this print statement in the callback function) but the value of "null" is printed instead. I believe this is a destructuring specific issue as I am able to print "5" by using this.state.timeRemaining in the console.log() statement instead. Any ideas why this is? Does this have anything to do with the context?
class Favr extends Component {
constructor(props) {
super(props);
this.state = {detailsAreShowing: false, timeRemaining: null};
this.showDetails = this.showDetails.bind(this);
}
componentWillMount() {
const { timeRemaining: swag } = this.state;
const { favr: {expirationTime} } = this.props;
let remainingTimeInMil = expirationTime.getTime() - Date.now();
this.setState({timeRemaining: 5}, () => {
console.log(swag); // prints null
});
...
}
...
}
That's because you are reading the declared variable at the first line of
componentWillMount
method which it's not updated. Even if you do not rename it it will printnull
as well. When you readthis.state.timeRemaining
again it provides the updated value.