All files / src/hooks/common useWindowCounter.tsx

11.11% Statements 4/36
0% Branches 0/6
0% Functions 0/10
11.76% Lines 4/34

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 55 56 57 58 59 60 61 62 63 64 65 66 67 68      520x                 520x               520x                   520x                                                                          
import { safeParse } from "@utils/index";
import React from "react";
 
const getWindowArray = () => {
  try {
    const storage = localStorage.getItem("window-refID");
    return storage ? safeParse(storage) : [];
  } catch {
    return [];
  }
};
 
const setWindowArray = (data: string[]) => {
  try {
    localStorage.setItem("window-refID", JSON.stringify(data));
  } catch (err) {
    console.warn(err);
  }
};
 
const removeWindow = (windowID: string) => {
  try {
    const array = getWindowArray();
    const newArray = array.filter((winID: string) => winID !== windowID);
    setWindowArray(newArray);
  } catch (err) {
    console.warn(err);
  }
};
 
const useWindowCounter = () => {
  const [isMainWindow, setIsMainWindow] = React.useState<boolean>(true);
  const windowRefID = React.useRef<string>("");
 
  const deleteHandler = () => {
    if (windowRefID.current) {
      removeWindow(windowRefID.current);
    }
  };
 
  React.useEffect(() => {
    const newID = Date.now().toString();
    windowRefID.current = newID;
    const array = getWindowArray();
 
    if (array.length > 0) {
      setIsMainWindow(false);
    }
 
    setWindowArray([...array, newID]);
 
    return () => deleteHandler();
  }, []);
 
  React.useEffect(() => {
    window.addEventListener("beforeunload", deleteHandler);
    // Removed 'unload' listener to reduce redundancy and potential conflicts
 
    return () => {
      window.removeEventListener("beforeunload", deleteHandler);
    };
  }, []);
 
  return { isMainWindow };
};
 
export default useWindowCounter;