Reputation: 561
I have a timer that work authomatically.But I want to add new feature to it. When I click it it should stop,when I click second time it should work.I used componentWillMount to create it.But it have some problems that I can not solve.
import React from 'react';
import ReactDOM from 'react-dom';
class Clock extends React.Component {
constructor(props) {
super(props);
this.state = { date: new Date(), status: true };
this.handleStatus = this.handleStatus.bind(this);
}
componentDidMount() {
if (this.state.status) {
const oneSecond = 1000;
this.clear = setInterval(() => {
this.setState({ date: new Date() });
}, oneSecond);
}
}
componentWillMount() {
if (!this.state.status) {
clearInterval(this.clear);
}
}
handleStatus() {
this.setState({ status: !this.state.status });
}
render() {
console.log(this.state.status);
return (
<div className="fs-5 fw-bold text-primary">
{this.state.date.toLocaleTimeString()}
<br />
<button className="btn btn-warning" onClick={this.handleStatus}>
Tikla
</button>
</div>
);
}
}
export default Clock;
Upvotes: 1
Views: 291
Reputation: 1663
Try like this.
componentDidMount() {
if (this.state.status) {
const oneSecond = 1000;
this.clear = setInterval(() => {
this.setState({ date: new Date() });
}, oneSecond);
}
}
handleStatus() {
if(this.state.status){
clearInterval(this.clear);
}
else{
const oneSecond = 1000;
this.clear = setInterval(() => {
this.setState({ date: new Date() });
}, oneSecond);
}
this.setState({ status: !this.state.status });
}
You can confrim here. https://codesandbox.io/s/youthful-cdn-lpntx?file=/src/App.js
Upvotes: 2