The worm The worm - 3 months ago 47
Javascript Question

Why is my state undefined?

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

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

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

componentWillUnmount() {

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


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