All files / src/hooks/acquirer-api useListCategoriesCodes.tsx

57.57% Statements 19/33
29.03% Branches 9/31
50% Functions 3/6
65.51% Lines 19/29

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 69 70 71 72 73 74 75 76 77 78 79                  34x         1108x 1108x           1108x           1108x 1108x   1108x 116x 116x 116x     116x         1108x 122x 6x 6x 6x                 122x   1108x                     1108x                      
import { useEffect, useRef, useState } from "react";
import { MCCType } from "./MCCType";
import { useGetGlobalMerchantCategories } from "./useGlobalMerchantCategories";
 
interface Props {
  all?: boolean;
  searchTerm?: string;
  scrollBoxRef?: React.RefObject<HTMLDivElement>;
}
const useListCategories = ({
  all = false,
  searchTerm = "",
  scrollBoxRef,
}: Props = {}) => {
  const [data, setData] = useState<MCCType[]>([]);
  const [page, setPage] = useState(1);
  const {
    data: pageData,
    isLoading,
    isFetching,
    isError,
  } = useGetGlobalMerchantCategories({
    page: data.length > 20 && searchTerm ? 1 : page,
    all,
    searchTerm,
  });
 
  const BOTTOM_OFFSET_PX = 4;
  const searchQueryRef = useRef(false);
 
  useEffect(() => {
    setPage(1);
    setData([]);
    searchQueryRef.current = true;
 
    // Reset scroll position when a new search starts
    Iif (scrollBoxRef?.current) {
      scrollBoxRef.current.scrollTop = 0;
    }
  }, [searchTerm]);
 
  useEffect(() => {
    if (pageData?.data) {
      if (searchQueryRef.current) {
        setData(pageData?.data ?? []);
        searchQueryRef.current = false;
      } else E{
        if (data.length === 0 && pageData?.data) {
          setData(pageData.data);
        } else if (data.length > 0) {
          setData((prev) => [...prev, ...pageData.data]);
        }
      }
    }
    Iif (pageData?.data === null && !isLoading) setData([]);
  }, [pageData]);
  const handleScroll = (e: React.UIEvent<HTMLElement>) => {
    if (isLoading) return;
    const { scrollTop, clientHeight, scrollHeight } = e.currentTarget;
    const isNearBottom =
      scrollHeight - (scrollTop + clientHeight) <= BOTTOM_OFFSET_PX;
 
    if (isNearBottom && pageData?.total > data.length) {
      setPage((prev) => prev + 1);
    }
  };
 
  return {
    data,
    isLoading,
    isError,
    handleScroll,
    setPage,
    isFetching,
  };
};
 
export default useListCategories;