@open-tender/utils
Version:
A library of utils for use with Open Tender applications that utilize our cloud-based Order API.
74 lines (73 loc) • 3.11 kB
JavaScript
import { __awaiter } from "tslib";
import { useState, useEffect, useRef } from 'react';
import { makeFormErrors, validateCreditCard } from '../';
export const useCreditCardForm = (loading, error, data, cardType, addCard, callback, includeRecaptcha, revenue_center_id, kountSessionId, requireCardholderName = false) => {
const submitRef = useRef(null);
const recaptchaRef = useRef(null);
const [submitting, setSubmitting] = useState(false);
const [errors, setErrors] = useState({});
useEffect(() => {
if (loading === 'idle') {
setSubmitting(false);
if (error) {
setErrors(makeFormErrors(error));
if (recaptchaRef.current)
recaptchaRef.current.reset();
}
}
}, [loading, error]);
const handleSubmit = (evt) => __awaiter(void 0, void 0, void 0, function* () {
var _a, _b, _c, _d, _e;
evt === null || evt === void 0 ? void 0 : evt.preventDefault();
setErrors({});
if (!data || !cardType)
return;
const { card, errors: cardErrors } = validateCreditCard(data, cardType, requireCardholderName);
if (cardErrors) {
setErrors(cardErrors);
setSubmitting(false);
}
else {
const cardRc = revenue_center_id ? Object.assign(Object.assign({}, card), { revenue_center_id }) : card;
if (kountSessionId)
cardRc.kount_device_session_id = kountSessionId;
if (includeRecaptcha) {
try {
const isEnterpriseRecaptcha = ((_a = recaptchaRef.current) === null || _a === void 0 ? void 0 : _a.props.size) === 'invisible';
const token = isEnterpriseRecaptcha
? yield ((_b = recaptchaRef.current) === null || _b === void 0 ? void 0 : _b.executeAsync())
: (_c = recaptchaRef.current) === null || _c === void 0 ? void 0 : _c.getValue();
if (!token) {
setSubmitting(false);
setErrors({
form: 'Please complete the recaptcha before submitting'
});
}
else {
setSubmitting(true);
addCard(Object.assign(Object.assign({}, cardRc), { token }), callback);
}
}
catch (err) {
setSubmitting(false);
setErrors({
form: 'Please complete the recaptcha before submitting'
});
}
}
else {
setSubmitting(true);
addCard(cardRc, callback);
}
}
((_d = submitRef.current) === null || _d === void 0 ? void 0 : _d.blur) && ((_e = submitRef.current) === null || _e === void 0 ? void 0 : _e.blur());
});
return {
submitRef,
recaptchaRef,
data,
errors,
submitting,
handleSubmit
};
};