pause() api resets the countdown #198
-
|
I am trying to start and pause the countdown based on isRunning state, start() API works fine, but when I try to pause & restart the countdown it resets to the initial value. Any suggestions on how to fix this? Codesandbox : https://codesandbox.io/s/react-countdown-gq5n58 // App.js
import "./styles.css";
import Countdown from "./components/CountDown";
import React, { useState } from "react";
export default function App() {
const [isRunning, setIsRunning] = useState(false);
return (
<div className="App">
<Countdown isRunning={isRunning} />
{isRunning ? (
<button onClick={() => setIsRunning(false)} className="btn">
Pause
</button>
) : (
<button onClick={() => setIsRunning(true)} className="btn">
Start
</button>
)}
</div>
);
}
// Countdown.js
import React, { useRef, useEffect } from "react";
import Dayjs from "dayjs";
import Countdown, { zeroPad } from "react-countdown";
const CountdownTimer = ({ isRunning, setIsRunning }) => {
const countdownRef = useRef();
const renderer = ({ hours, minutes, seconds, total }) => {
console.log(total / 1000);
return (
<span>
{`${hours > 0 ? zeroPad(hours) + ":" : ""}${zeroPad(minutes)}:${zeroPad(
seconds
)}`}
</span>
);
};
useEffect(() => {
if (isRunning) {
countdownRef.current.api.start();
} else {
countdownRef.current.api.pause();
}
}, [isRunning]);
return (
<div className="countdown">
<Countdown
ref={countdownRef}
renderer={renderer}
autoStart={false}
date={Dayjs().add(45, "minutes")}
/>
</div>
);
};
export default CountdownTimer;API reference part of the documentation needs a few examples, |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment
-
|
Hi, try to persist your |
Beta Was this translation helpful? Give feedback.
Hi, try to persist your
datevalue as a component state (viauseState) and pass this value as adateprop into the countdown. Currently, it could be generating a new date on every rerender (wheneverisRunningis changing).