All files / src/features/Products/hooks useGetProductList.tsx

2.38% Statements 1/42
0% Branches 0/21
0% Functions 0/13
2.56% Lines 1/39

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 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136                                        1x                                                                                                                                                                                                                                      
import { ROWS_PER_PAGE, usePagination } from "@hooks/common/usePagination";
import { useStateEffect } from "@hooks/customReactCore";
import { useAppDispatch, useAppSelector } from "@redux/hooks";
import {
  disableDateFilter,
  selectQueryFilters,
  sorting as sortingReducer,
} from "@redux/slices/fundraisers";
import { selectQueryString, setSearchQueryByKey } from "@redux/slices/search";
import { useGetInfiniteProductsByType } from "@services/api/products/events";
import { mapTypeToQueryKey } from "@services/api/products/queryFactory";
import { encodedQueryFilterMap } from "@services/filtering";
import { useCallback, useMemo, useRef } from "react";
import { ProductData, TCampaignType } from "../types";
import { sanitizePhoneSearchQuery } from "./utils";
 
type Props = {
  type: TCampaignType;
};
 
export const useGetProductList = ({ type }: Props) => {
  const dispatch = useAppDispatch();
  const queryFilters = useAppSelector(selectQueryFilters);
  const sorting = useAppSelector(sortingReducer);
  const queryKey = mapTypeToQueryKey[type];
  const pageLoadingRef = useRef(false);
 
  const searchQuery = useAppSelector((state) =>
    selectQueryString(state, queryKey),
  );
  const queryFilter = useMemo(
    () => encodedQueryFilterMap(queryFilters),
    [queryFilters],
  );
 
  const { page, setPage } = usePagination(0, queryFilter?.products);
 
  const queryString = queryFilter.products ? `%3B${queryFilter.products}` : "";
 
  const sanitizedSearchQuery = sanitizePhoneSearchQuery(searchQuery ?? "");
 
  const {
    data,
    isFetchingNextPage,
    isFetching,
    isLoading,
    hasNextPage,
    fetchNextPage,
    isError,
  } = useGetInfiniteProductsByType(type)(
    {
      queryString,
      sorting,
      searchQuery: sanitizedSearchQuery,
    },
    {
      refetchOnWindowFocus: type === "invoice",
    },
  );
 
  const totalRows = data?.pages[0]?.total ?? 0;
 
  const allData = useMemo(() => {
    if (!data?.pages?.length) return [];
 
    return data.pages
      .filter((page): page is NonNullable<typeof page> => page?.data != null)
      .flatMap((page) => page.data);
  }, [data]);
 
  const handlePageChange = (
    event: React.ChangeEvent<unknown>,
    value: number,
  ) => {
    setPage(value);
  };
 
  const handleResetFilters = () => {
    dispatch(disableDateFilter());
  };
 
  const handleSearch = useCallback(
    (value: string) => {
      dispatch(
        setSearchQueryByKey({
          queryKey: queryKey || "",
          params: {
            value,
          },
        }),
      );
    },
    [queryKey],
  );
 
  const loadMore = useCallback(async () => {
    const isFetching = pageLoadingRef.current;
 
    if (!isFetching && hasNextPage) {
      pageLoadingRef.current = true;
      const newPage = page + 1;
      const { isSuccess } = await fetchNextPage({
        pageParam: newPage,
      });
      if (isSuccess) setPage(newPage);
      pageLoadingRef.current = false;
    }
  }, [isFetchingNextPage, page, hasNextPage]);
 
  useStateEffect(() => {
    setPage(1);
  }, [sorting, searchQuery, queryString, type]);
 
  const usedData = allData ?? [];
 
  return {
    data,
    isLoading: isLoading || (isFetching && isFetchingNextPage),
    isFetchingNextPage,
    isError,
    page,
    setPage: () => setPage((current) => current + 1),
    setPageDispatcher: setPage,
    handlePageChange,
    totalRows,
    rowsPerPage: ROWS_PER_PAGE,
    allRows: usedData as ProductData[],
    queryKey,
    searchQuery,
    hasFilters: Boolean(queryString),
    handleResetFilters,
    handleSearch,
    loadMore,
  };
};