All files / src/features/Merchants/MerchantSidePanel/hooks useUpdateReserveToggle.ts

96.42% Statements 27/28
70% Branches 7/10
100% Functions 9/9
96.29% Lines 26/27

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          21x                 536x 536x 536x   536x   536x 122x 116x         536x       4x       4x   4x           4x     536x 2x     536x 2x 2x     536x 2x 2x     536x     21x             261x   21x             261x  
import { useState, useEffect } from "react";
import { MERCHANT_SIDE_PANEL_PREVIEW_API_KEYS } from "../constants";
import { useQueryClient } from "react-query";
import useUpdateMerchant from "./useUpdateMerchant";
 
export const useUpdateReserveToggle = ({
  id,
  defaultValue,
  reserveKey,
}: {
  id: number;
  defaultValue?: boolean;
  reserveKey: "minimumReserveBPS" | "rollingReserveBPS"; // extend as needed
}) => {
  const { updateMerchantMutation } = useUpdateMerchant(undefined, id);
  const queryClient = useQueryClient();
  const { mutateAsync, isLoading } = updateMerchantMutation;
 
  const [reserveRequired, setReserveRequired] = useState(Boolean(defaultValue));
 
  useEffect(() => {
    if (isLoading) return;
    Iif (defaultValue !== undefined && defaultValue !== reserveRequired) {
      setReserveRequired(Boolean(defaultValue));
    }
  }, [defaultValue, isLoading]);
 
  const handleUpdate = async (
    value: number | null,
    cb?: (data?: any) => void,
  ) => {
    const data = await mutateAsync({
      [reserveKey]: value || 0,
    });
 
    queryClient.setQueryData(
      [MERCHANT_SIDE_PANEL_PREVIEW_API_KEYS.GET, id],
      (oldData: any) => ({
        ...oldData,
        [reserveKey]: data?.[reserveKey] || 0,
      }),
    );
 
    cb?.(data);
  };
 
  const checkboxCallback = (data?: any) => {
    setReserveRequired(Boolean(data[reserveKey]));
  };
 
  const handleChange = async (value: number | null) => {
    setReserveRequired(Boolean(value));
    await handleUpdate(value, checkboxCallback);
  };
 
  const handleSubmit = async (data: Record<string, any>, cb?: () => void) => {
    await handleUpdate(Number(data[reserveKey]));
    cb?.();
  };
 
  return { reserveRequired, handleChange, handleSubmit, isLoading };
};
 
export const useUpdateMinimumReserve = ({
  id,
  defaultValue,
}: {
  id: number;
  defaultValue?: boolean;
}) =>
  useUpdateReserveToggle({ id, defaultValue, reserveKey: "minimumReserveBPS" });
 
export const useUpdateRollingReserve = ({
  id,
  defaultValue,
}: {
  id: number;
  defaultValue?: boolean;
}) =>
  useUpdateReserveToggle({ id, defaultValue, reserveKey: "rollingReserveBPS" });