0

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
        });
        ...
    }
    ...
}
Dkpalea
  • 13
  • 4

2 Answers2

0

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.

cesarcosta99
  • 11
  • 1
  • 4
  • Hmmm, I was under the impression that I was merely referencing the state value when declaring my destructured state constant. Is there a recommended way that I could destructure and maintain access to the latest state values? – Dkpalea Nov 29 '18 at 00:50
  • Exactly. Nope, you just read it again when you need or read after update it which seems it's your case. – cesarcosta99 Nov 29 '18 at 01:04
0

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.

Thai Duong Tran
  • 2,453
  • 12
  • 15