Reputation: 237
I am trying to stop the timer when the state count hits 0 or the state isStopped is true then it should stop it at that specific number. I am not familiar with class programming with react and am having difficulty implementing this.
I tried to look it up but I am not familiar with how to implement this using component did mount. I believe my logic should be correct on the component did mount portion however it never stops when it is 0 on the react app
Here is my code
import React, { Component } from "react";
import "./index.css";
export default class Timer extends Component {
constructor(props) {
super(props);
this.state = {
count: 10,
isStopped: false,
};
}
handleClick = () => {
this.setState({ isStopped: !this.state.isStopped });
console.log(this.state.isStopped);
};
render() {
return (
<div className="mt-100 layout-column align-items-center justify-content-center">
<div className="timer-value" data-testid="timer-value">
{this.state.count}
</div>
<button
className="large"
data-testid="stop-button"
onClick={this.handleClick}
>
Stop Timer
</button>
</div>
);
}
componentDidMount() {
if (this.state.count > 0 && this.state.isStopped == false) {
this.myInterval = setInterval(() => {
this.setState({ count: this.state.count - 1 });
}, 1000);
}
}
}
Any help would be appreciated thank you :)
Upvotes: 1
Views: 120
Reputation: 4482
in componentDidMount()
, clear the interval a/c to state:
componentDidMount() {
if (this.state.count > 0 && this.state.isStopped == false) {
this.myInterval = setInterval(() => {
if (this.state.isStopped) {
clearInterval(this.myInterval);
return;
}
this.setState({ count: this.state.count - 1 });
}, 1000);
}
}
Upvotes: 1
Reputation: 2194
You can use the below login
componentDidMount() {
if (this.state.count > 0) {
this.myInterval = setInterval(() => {
if (this.state.isStopped) {
clearInterval(this.myInterval);
return;
}
this.setState({ count: this.state.count - 1 });
}, 1000);
}
}
Upvotes: 0