All files / src/components/Merchants/MerchantPreview/hooks useMerchantFilesQuery.tsx

94.44% Statements 17/18
61.53% Branches 8/13
100% Functions 6/6
93.75% Lines 15/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 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                                          109x           521x     521x     11x   11x   5x         5x   5x                         37x       521x 1x         521x 76x   5x     521x          
import { customInstance } from "@services/api";
import { useMemo } from "react";
import { useInfiniteQuery } from "react-query";
import { useAppDispatch } from "@redux/hooks";
import {
  MERCHANT_SIDE_PANEL_PREVIEW_API_KEYS,
  GENERAL_STALE_TIME_15,
} from "features/Merchants/MerchantSidePanel/constants";
import { ROWS_PER_PAGE } from "@hooks/common/usePagination";
 
type Props = {
  id: number;
  refetchOnMount: boolean;
  enabled: boolean;
  setPermissionError: (
    promise: PromiseSettledResult<any>,
    permissionKey: string,
    dispatch: any,
  ) => void;
};
 
export const useMerchantFilesQuery = ({
  id,
  refetchOnMount,
  enabled,
  setPermissionError,
}: Props) => {
  const dispatch = useAppDispatch();
 
  // Documents query
  const documentsQuery = useInfiniteQuery(
    [MERCHANT_SIDE_PANEL_PREVIEW_API_KEYS.GET_FILES, id],
    async ({ pageParam = 1 }) => {
      const url = `/accounts/${id}/files?page=${pageParam}&max=${ROWS_PER_PAGE}&sort=-updatedAt&filter=isUploaded:true`;
 
      const response = await customInstance({ url });
 
      const promise = {
        status: "fulfilled",
        value: response,
      } as PromiseSettledResult<any>;
 
      setPermissionError(promise, "list-documents", dispatch);
 
      return {
        data: response?.data || [],
        total: response.total,
        currentPage: pageParam,
        hasNextPage: pageParam * ROWS_PER_PAGE < response.total,
      };
    },
    {
      refetchOnWindowFocus: false,
      refetchOnMount,
      enabled,
      staleTime: GENERAL_STALE_TIME_15,
      getNextPageParam: (lastPage) =>
        lastPage.hasNextPage ? lastPage.currentPage + 1 : undefined,
    },
  );
 
  const loadNextFilesPage = () => {
    Iif (documentsQuery.hasNextPage && !documentsQuery.isFetchingNextPage) {
      documentsQuery.fetchNextPage();
    }
  };
 
  const allItems = useMemo(() => {
    if (!documentsQuery.data) return [];
 
    return documentsQuery.data?.pages.flatMap((page) => page.data) || [];
  }, [documentsQuery.data]);
 
  return {
    documentsQuery: { ...documentsQuery, data: allItems },
    loadNextFilesPage,
  };
};