useCheckPassword.ts

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) => {
    if (propsId !== undefined) {
      mutate({
        userId: propsId,
        password: data.password,
      });

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

→ mutate가 실행되어 성공상태가 되면 인수로 전달받은 onSuccess함수가 실행이 됨. onSuccess함수는 props로 받은 userPassword함수에 react-hook-form의 watch를 통해 실시간으로 password를 감시해 넣어주고 있으며, onRequestSubmit있는 경우 onRequestSubmit함수를 실행하고 있음.