The worm The worm - 9 days ago 4
Javascript Question

React function working on componentDidMount but not onClick

if I change my code from this

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


to this:

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

<p><input type="submit" value="Start Timer!" onClick={this.startTimer}/></p>


I can get an error saying
Cannot read property 'timer' of null
pointing to the
let interval
line

Why would I get this? (binding error?)

I thought this next part would solve that:

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


Maybe some stuff has not mounted? I cant work out why it works onMount but not onClick

Answer

You probably have to change this.timer = this.timer.bind(this); to this.startTimer = this.startTimer.bind(this); in your constructor function.

Comments