All files / src/hooks/common useInternetStatus.ts

57.89% Statements 11/19
25% Branches 1/4
50% Functions 3/6
57.89% Lines 11/19

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    1x   6x 6x   6x                               1x 1x   1x 1x 1x 1x           6x            
import { useEffect, useRef, useState } from "react";
 
const delay = 5000;
function useInternetStatus() {
  const [isOnline, setIsOnline] = useState<boolean>(navigator.onLine);
  const timeoutRef = useRef<NodeJS.Timeout | null>(null);
 
  useEffect(() => {
    function onlineHandler() {
      setIsOnline(true);
      if (timeoutRef.current) {
        clearTimeout(timeoutRef.current);
        timeoutRef.current = null;
      }
    }
 
    function offlineHandler() {
      timeoutRef.current = setTimeout(() => {
        setIsOnline(false);
        timeoutRef.current = null;
      }, delay);
    }
 
    window.addEventListener("online", onlineHandler);
    window.addEventListener("offline", offlineHandler);
 
    return () => {
      window.removeEventListener("online", onlineHandler);
      window.removeEventListener("offline", offlineHandler);
      Iif (timeoutRef.current) {
        clearTimeout(timeoutRef.current);
      }
    };
  }, []);
 
  return {
    isOnline,
  };
}
 
export default useInternetStatus;