brilliant-orangeB
Refine2y ago
4 replies
brilliant-orange

When I use useForm and fetch twice call api

export const CancelModal = ({
  subscriptions = [],
  membershipStateType,
}: CancelModalProps) => {
  const {
    register,
    setValue,
    formState: { errors },
    handleSubmit,
    reset,
    refineCore: { onFinish },
  } = useForm<ICancelDetail, HttpError>({
    refineCoreProps: {
      resource: 'membership/cancel',
      // action: 'create',
      // redirect: 'list',
    },
  });
  const [open, setOpen] = useState(false);
  const [memo, setMemo] = useState('');

  const handleOpen = () => {
    setOpen(true);
  };
  const handleClose = () => {
    setOpen(false);
  };

  const handleCancel = async (
    memberId: string,
    subscriptionId: string,
    state: string,
  ) => {
    try {
      const url = `${process.env.NEXT_PUBLIC_API_URL}/membership/cancel`;

      const response = await fetch(url, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({ memberId, subscriptionId, state, memo }),
      });

      if (response.ok) {
        onFinish(response).then(() => {
          reset();
        });
        handleClose();
        window.location.reload();
      } else {
        console.error('Failed to cancel subscription');
      }
    } catch (error) {
      console.error('Error cancelling subscription: ', error);
    }
  };

...
 <Button
                    sx={buttonStyle}
                    onClick={(e) => {
                      e.preventDefault();
                      handleCancel(
                        subscription.member_id,
                        subscription.subscription_id,
                        membershipStateType,
                      );
                    }}
                  >
                    {membershipStateType === 'U'
                      ? '구독 해지'
                      : '멤버십 즉시 해지'}
                  </Button>

When the button is clicked, fetch and useForm each call the API. How to only call fetch?
Was this page helpful?