Quantcast
Channel: Active questions tagged react-native+typescript - Stack Overflow
Viewing all articles
Browse latest Browse all 6287

React countdown timer

$
0
0

I have a countdown timer snippet in react as below:

const [remainingTime, setRemainingTime]: [number, Dispatch<SetStateAction<number>>] = useState<number>(0);const [updatedTime, setUpdatedTime]: [number, Dispatch<SetStateAction<number>>] = useState<number>(0);const referenceTime = useRef<number>(0); // new Date().getTime()const intervalRef = useRef<number>(updatedTime);const decreaseTime = () =>        setUpdatedTime((prevState) => {            if (prevState > 1) {                    return parseFloat(((updatedTime * 1000 + referenceTime.current - Date.now()) / 1000).toFixed(0));            } else {                setRemainingTime(0);                return 0;            }        });    useEffect(() => {        if (remainingTime > 0) {            intervalRef.current = setInterval(decreaseTime, 1000) as unknown as number;        }        return () => clearInterval(intervalRef.current);}, [remainingTime]);

Everything works fine till I want to add an increment and decrement option to it. It is necessary to use Date.now() and the referenceTime because this module is used in react-native and it must work in background mode, so where should I change something to upgrade the state correctly. I tried the below solutions:

setUpdatedTime((prevState) => prevState + 10)

and

setUpdatedTime((prevState) => updatedTime + 10)

Update:https://codesandbox.io/s/react-countdown-timer-lr9sb

Thanks for the help. :)


Viewing all articles
Browse latest Browse all 6287

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>