Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trialFelix Olonde
4,164 PointsMaking the stopwatch tick
Am trying to make the stopwatch tick but I get the error Cannot read property 'running' of undefined
my code is as below
class Stopwatch extends React.Component {
constructor(){
super();
this.state = {
running: false,
elapsedTime: 0,
previousTime: 0,
}
};
componentDidMount() {
this.interval = setInterval(this.onTick, 100);
}
componentWillUnmount() {
clearInterval(this.interval);
}
onTick() {
if(this.state.running) {
const now = Date.now();
this.setState({
previousTime: now,
elapsedTime: this.state.elapsedTime + (now - this.state.previousTime),
});
}
console.log('onTick');
}
onStart() {
this.setState({
running: true,
previousTime: Date.now(),
});
}
onStop() {
this.setState({
running: false
});
}
onReset() {
this.setState({
elapsedTime: 0,
previousTime: Date.now(),
});
}
render() {
var seconds = Math.floor(this.state.elapsedTime / 1000);
return (
<div className="stopwatch">
<h2>Stopwatch</h2>
<div className="stopwatch-time">{seconds}</div>
{ this.state.running ?
<button onClick={this.onStop.bind(this)}>Stop</button>
:
<button onClick={this.onStart.bind(this)}>Start</button>
}
<button onClick={this.onReset.bind(this)}>Reset</button>
</div>
);
}
}
gevuong
2,377 Pointsgevuong
2,377 PointsYou are very close! You need to bind onTick() to "this" with the following line of code in the constructor function:
this.onTick = this.onTick.bind(this);
From my understanding, it is preferred to bind methods to "this" in the constructor function because an instance of the function that is bounded to "this" only needs to be created once in this case. In other words, bind() creates a new function, which means every time render() is called, a new function is created, which is unnecessary in this case. Hope this helps.