All files / src/hooks/enterprise-api/merchants/watchlist useAddMerchantToWatchlist.tsx

34.78% Statements 8/23
0% Branches 0/7
25% Functions 1/4
34.78% Lines 8/23

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                        117x 507x 507x 507x   507x                                                                 507x       507x       507x        
import { showMessage } from "@common/Toast";
import { useUpdateMerchantsLists } from "@components/Merchants/MerchantPreview/hooks/useGetTeamMembers";
import {
  QKEY_LIST_ACQUIRER_MERCHANTS,
  QKEY_LIST_ENTERPRISE_STATS,
  QKEY_LIST_MERCHANTS,
} from "@constants/queryKeys";
import { MERCHANT_SIDE_PANEL_PREVIEW_API_KEYS } from "@features/Merchants/MerchantSidePanel/constants";
import { customInstance } from "@services/api";
import { checkPortals } from "@utils/routing";
import { useQueryClient } from "react-query";
 
const useWatchlist = (queryKey?: string) => {
  const { updateData, revertChange } = useUpdateMerchantsLists(queryKey);
  const queryClient = useQueryClient();
  const { isEnterpriseTable } = checkPortals();
 
  const editMerchantWatchlist = async (
    id: number,
    name: string,
    add = true,
  ) => {
    try {
      await queryClient.cancelQueries(queryKey);
      updateData(id, { watchlist: add }, { updateMerchantPreview: true });
      const url = `/merchants/${id}/watchlist`;
      await customInstance({
        url: url,
        method: "POST",
        data: { watchlist: add },
      });
 
      // Here we can fetch the last query
      if (isEnterpriseTable)
        queryClient.invalidateQueries(QKEY_LIST_ENTERPRISE_STATS);
      if (!isEnterpriseTable) {
        queryClient.invalidateQueries(QKEY_LIST_MERCHANTS);
        queryClient.invalidateQueries(QKEY_LIST_ACQUIRER_MERCHANTS);
      }
 
      queryClient.invalidateQueries([
        MERCHANT_SIDE_PANEL_PREVIEW_API_KEYS.GET,
        id,
      ]);
    } catch (error) {
      revertChange();
      showMessage("Error", "Whoops.. an error occured. Please try again");
    }
  };
 
  const addMerchantToWatchlist = (merchantId: number, name: string) => {
    editMerchantWatchlist(merchantId, name);
  };
 
  const removeMerchantFromWatchlist = (merchantId: number, name?: string) => {
    editMerchantWatchlist(merchantId, name || "", false);
  };
 
  return { addMerchantToWatchlist, removeMerchantFromWatchlist };
};
 
export default useWatchlist;