Hey everyone,
I’m working on the Pomodoro timer, all has been smooth but man, I’ve hit a snag. I’m trying to adhere to that all too revered DRY principle with some dynamic state keys.
Right now I’m working on getting the timer to decrement with setInterval()
Hardcoding the changes in the state gets the result I want, but then I’ll be needing to make a different hard-coded version for each state. Not ideal design.
Here is the code I’m working with:
WORKING HARDCODE
countDown = () => {
myTimer = setInterval(() => {
if (this.state.sessionTime < 0) {
clearInterval(myTimer);
return;
}
this.setState({ sessionTime: this.state.sessionTime - 1 });
}, 1000);
};
FAILED DYNAMIC ATTEMPT
countDown = (clock) => {
myTimer = setInterval(() => {
if (this.state[clock] < 0) {
clearInterval(myTimer);
return;
}
this.setState({ [clock]: this.state[clock] - 1 });
}, 1000);
};
I know using brackets is the go-to way when working with dynamic objects but in this instance, I’m struggling here. Really looking for some guidance here! Thanks all.