All files / src/hooks/common useObserveHTMLNode.ts

56.25% Statements 9/16
22.22% Branches 2/9
60% Functions 3/5
56.25% Lines 9/16

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          2x         19x                   19x         19x 3x         19x     2x 19x             19x    
import { useCallback, useEffect } from "react";
import { useInView } from "react-intersection-observer";
import { throttle } from "lodash";
import { ROWS_PER_PAGE } from "./usePagination";
 
export const useObserveHTMLNode = (
  loadingRef: React.MutableRefObject<boolean>,
  onIntersect: any,
  throttleDuration = 1500,
) => {
  const handleIntersect = useCallback(
    throttle(() => {
      if (!loadingRef.current) {
        loadingRef.current = true;
        onIntersect();
      }
    }, throttleDuration),
    [onIntersect, throttleDuration],
  );
 
  const [ref, inView] = useInView({
    threshold: 0.1,
    triggerOnce: false,
  });
 
  useEffect(() => {
    Iif (inView) {
      handleIntersect();
    }
  }, [inView]);
 
  return ref;
};
 
export const useTargetRef = ({ page, totalRows, setPage, loadingRef }: any) => {
  const targetRef = useObserveHTMLNode(loadingRef, () => {
    const pageNo = page?.current ?? page;
    if (pageNo < Math.ceil(totalRows / ROWS_PER_PAGE)) {
      setPage();
    }
  });
 
  return targetRef;
};