vydimitrov / react-countdown-circle-timer

Lightweight React/React Native countdown timer component with color and progress animation based on SVG
MIT License
692 stars 87 forks source link

Restart timer component with new duration after onComplete event in React #205

Closed EmmS21 closed 2 years ago

EmmS21 commented 2 years ago

Trying to create an event handler that changes the duration of the timer each time the timer reaches zero.

The clock initially runs down from 5 seconds, when it reaches zero I change the state, then use this to change the new value assigned to the clock.

For a more practical example. When the clock initially runs to zero, I change my stage state to 2, setting the timer to 6 seconds. When this clocks runs down, I change my stage state to 3, setting the timer to 7 seconds and so on, until I stop at stage 5

This is my code:

  const [ timer, setTimer ] = useState(5)
  const [stage, setStage] = useState(1)
  const timerMap = {
        2: 6,
        3: 7,
        4: 8,
        5: 9
    }
  const changeTimeHandler = (timer, setTimer) => {
        setStage(stage+1)
        setTimer(timerMap[stage])
        return { delay:1 }
  }
    console.log(timer)
  return (
    <div className="App">
      <div className="timer-wrapper">
        <CountdownCircleTimer
          isPlaying
          duration={timer}
          colors={["#004777", "#F7B801", "#A30000", "#A30000"]}
          colorsTime={[10, 6, 3, 0]}
          onComplete={() => (changeTimeHandler(timer, setTimer))}
          size={100}
        >
          {renderTime}
        </CountdownCircleTimer>
      </div>
    </div>
  );

When I run my code I get the error:

Warning: Received NaN for the 'strokeDashoffset' attribute. If this is expected, cast the value to a string.

Any ideas what's going wrong?

vydimitrov commented 2 years ago

Hey @EmmS21, when you change the time/duration the timer will not reset its state but it will continue from where it was left. I guess what you want is restart the timer and to do that you just need to pass a key prop to the CountdownCircleTimer like so < CountdownCircleTimer key={timer} ... >. This will make sure to restart the timer when you change the duration.

vydimitrov commented 2 years ago

I am closing this issue due to inactivity,