How can I access my component state through destructuring?

131 Views Asked by At

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

There are 2 best solutions below

2
On

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 print null as well. When you read this.state.timeRemaining again it provides the updated value.

0
On

There is a problem with your understanding and using of variables and references in JS.

  • By destructuring / deconnstructing const {timeRemaining: swag} = this.state, you are creating a new variable swag. This variable will have new memory allocated to it, updating timeRemaining will not change value of swag as at the time of assignment, timeRemaining has value of null. Assignment by referencing only works with object in JS.

  • Also, not directly related to your question, but it's worth knowing that it's never a good idea to use componentWillMount with React. This lifecycle method has been deprecated since React 16.3: https://reactjs.org/docs/react-component.html#unsafe_componentwillmount.