The worm The worm - 16 days ago 16
Javascript Question

Why is my state undefined?

Trying to follow a simple clock/countdown tutorial in React:

constructor(props) {
super(props);
this.state = {
secondsRemaining: 10
};
}

componentDidMount(){
let interval = setInterval(this.timer, 1000);
this.setState({ secondsRemaining: this.state.secondsRemaining })
this.setState({ interval: interval });
};

componentWillUnmount() {
clearInterval(this.state.interval);
};

timer(){
this.setState({ secondsRemaining: this.state.secondsRemaining -1 });
};


Very obvious what everything does but when I run it, I get an error saying
cannot read property secondsRemaining of undefined
in the timer function

It is probably something stupid I have missed out but I just cannot see it

followed the answer to this question: setInterval in a React app

Answer

The myfunction.bind() method specifies what this will be refering to inside the method when its being called. To be sure that when you call this.timer() you are actually refering to your components state and not the object thats invoking it you will have to pass this.timer.bind(this).