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 trial
Kristian Woods
23,414 PointsWhy couldn't the Timer example have been simpler?
I have created the same timer, with the exact same functionality - yet, doesn't include all the excess e.g. elapsed time etc. However, I might be missing something in mine, that Guil has in his?
However, here is my version
class App extends Component {
state = {
isRunning: false,
time: 0
};
tick = () => {
this.setState(prevState => {
return {
time: (prevState.time += 1)
};
});
};
handleTimer = () => {
this.setState(prevState => {
return {
isRunning: !prevState.isRunning
};
});
if (!this.state.isRunning) {
this.intervalID = setInterval(() => this.tick(), 1000);
} else {
clearInterval(this.intervalID);
}
};
handleReset = () => {
this.setState(prevState => {
return {
time: 0
};
});
};
render() {
return (
<div className="App">
<h1>{this.state.time}</h1>
<button onClick={this.handleTimer}>
{this.state.isRunning ? "Stop" : "Start"}
</button>
<button onClick={this.handleReset}>Reset</button>
</div>
);
}
}
Kristian Woods
23,414 PointsKristian Woods
23,414 Pointsvideo: https://teamtreehouse.com/library/update-the-stopwatch-state-with-componentdidmount