Skip to content

Commit

Permalink
setInterval inside the App component
Browse files Browse the repository at this point in the history
  • Loading branch information
rocketkai committed Jun 11, 2022
1 parent ac79de0 commit 6c7c6c8
Showing 1 changed file with 23 additions and 3 deletions.
26 changes: 23 additions & 3 deletions src/App.js
Expand Up @@ -3,14 +3,34 @@ import logo from "./logo.png";
import "./App.css";

class App extends React.Component {
constructor(props) {
super(props);
// Initialise component state to contain "date" attribute with current date and time
this.state = { date: new Date() };
}

componentDidMount() {
// Set date value in state every second to current date and time
// Save setInterval timer ID in class variable for teardown in another class method
this.timerId = setInterval(() => {
this.setState({
date: new Date(),
});
}, 1000);
}

componentWillUnmount() {
// Teardown setInterval timer with timer ID saved as class variable
clearInterval(this.timerId);
}

render() {
return (
<div className="App">
<header className="App-header">
<img src={logo} className="App-logo" alt="logo" />
<p>
Edit <code>src/App.js</code> and save to reload.
</p>
{/* Render date value that is stored in state */}
<p>{this.state.date.toString()}</p>
</header>
</div>
);
Expand Down

0 comments on commit 6c7c6c8

Please sign in to comment.