useCheckPassword.ts

import { useState } from 'react';

import { useMutation } from '@tanstack/react-query';
import KstadiumAPI from 'apis/kstadiumAPI';
import { CheckAuthRequestBody } from 'apis/kstadiumAPI/member/types';

const useCheckPassword = (onSuccess: VoidFunction) => {
  const [errorMsg, setErrorMsg] = useState<string>(``);
  const { mutate, isError } = useMutation({
    mutationFn: (pwd: CheckAuthRequestBody) => KstadiumAPI.checkAuth(pwd),
    onSuccess,
    onError: () => {
      setErrorMsg(`Please check your password.`);
    },
  });
  return { mutate, errorMsg, isError };
};

export default useCheckPassword;
const EnterPasswordModal: React.FC<PasswordModalProps> = ({
  onRequestClose,
  onRequestSubmit,
  cantGoBack,
  userPassword,
  ...props
}) => {
  const {
    handleSubmit,
    reset,
    control,
    trigger,
    clearErrors,
    setValue,
    setError,
    watch,
    formState: { errors, isValid, isSubmitting },
  } = useForm<ConfirmPasswordData>({
    defaultValues: {
      password: ``,
    },
    mode: `onChange`,
  });
 
  const watchPassword = watch(`password`);
  const onSuccess = useCallback(() => {
    userPassword(watchPassword);

    if (onRequestSubmit) onRequestSubmit();
  }, [onRequestSubmit, userPassword, watchPassword]);

  const { mutate, errorMsg, isError } = useCheckPassword(onSuccess);

  const onSubmit: SubmitHandler<ConfirmPasswordData> = (data) => {
    console.log(`propsId`, propsId);
    if (propsId !== undefined) {
      mutate({
        userId: propsId,
        password: data.password,
      });

      if (isError) {
        setError(`password`, {
          type: `manual`,
          message: errorMsg,
        });
      }
      onRequestClose();
    }
    console.log(data);
  };