All files / react-app/src/hooks/useCountdown index.ts

91.66% Statements 22/24
75% Branches 3/4
100% Functions 9/9
91.3% Lines 21/23

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54                    73x 15x 15x   15x 4x     15x 2x       15x 1x 1x     15x 25x         25x     15x 15x 7x     8x 25x     8x 8x       15x    
// credit: https://usehooks-ts.com/react-hook/use-countdown
 
import { useCallback, useEffect, useState } from "react";
 
type CountdownControllers = {
  startCountdown: () => void;
  stopCountdown: () => void;
  resetCountdown: () => void;
};
 
export const useCountdown = (minutesToCountDown: number): [number, CountdownControllers] => {
  const [count, setCount] = useState<number>(minutesToCountDown);
  const [isCountdownRunning, setIsCountdownRunning] = useState<boolean>(false);
 
  const startCountdown = () => {
    setIsCountdownRunning(true);
  };
 
  const stopCountdown = useCallback(() => {
    setIsCountdownRunning(false);
  }, []);
 
  // Will set running false and reset the seconds to initial value
  const resetCountdown = useCallback(() => {
    stopCountdown();
    setCount(minutesToCountDown);
  }, [stopCountdown, minutesToCountDown]);
 
  const countdownCallback = useCallback(() => {
    Iif (count === 0) {
      stopCountdown();
      return;
    }
 
    setCount((oldCount) => oldCount - 1);
  }, [count, stopCountdown]);
 
  useEffect(() => {
    if (isCountdownRunning === false) {
      return;
    }
 
    const id = setInterval(() => {
      countdownCallback();
    }, 1000);
 
    return () => {
      clearInterval(id);
    };
  }, [isCountdownRunning, countdownCallback]);
 
  return [count, { startCountdown, stopCountdown, resetCountdown }];
};