@open-tender/utils
Version:
A library of utils for use with Open Tender applications that utilize our cloud-based Order API.
75 lines (74 loc) • 2.67 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.useGiftCardForm = void 0;
const react_1 = require("react");
const utils_1 = require("../utils");
const useGiftCardForm = (creditCards, loading, error, update, add, callback, giftCardId) => {
const submitRef = (0, react_1.useRef)(null);
const inputRef = (0, react_1.useRef)(null);
const customerCardId = creditCards[0].customer_card_id;
const [data, setData] = (0, react_1.useState)({
amount: '',
customer_card_id: customerCardId
});
const [errors, setErrors] = (0, react_1.useState)({});
const [submitting, setSubmitting] = (0, react_1.useState)(false);
const options = creditCards.map(i => {
return {
name: `${i.card_type_name} ending in ${i.last4}`,
value: `${i.customer_card_id}`
};
});
const fields = [
{
label: 'Amount',
name: 'amount',
type: 'text'
},
{
label: 'Credit Card',
name: 'customer_card_id',
type: 'select',
options
}
];
(0, react_1.useEffect)(() => {
var _a, _b;
if (loading === 'idle') {
setSubmitting(false);
if (error) {
const errs = (0, utils_1.makeFormErrors)(error);
if (errs.amount && errs.amount.includes('money')) {
errs.amount = 'Please enter a positive dollar amount';
}
setErrors(errs);
((_a = inputRef.current) === null || _a === void 0 ? void 0 : _a.focus) && ((_b = inputRef.current) === null || _b === void 0 ? void 0 : _b.focus());
}
}
}, [loading, error]);
const handleChange = (name, value) => {
setData(Object.assign(Object.assign({}, data), { [name]: value }));
};
const handleSubmit = (evt) => {
var _a, _b;
evt === null || evt === void 0 ? void 0 : evt.preventDefault();
setSubmitting(true);
if (!data.customer_card_id) {
data.customer_card_id = customerCardId;
}
data.customer_card_id = parseInt(`${data.customer_card_id}`);
giftCardId ? update(giftCardId, data, callback) : add(data, callback);
((_a = submitRef.current) === null || _a === void 0 ? void 0 : _a.blur) && ((_b = submitRef.current) === null || _b === void 0 ? void 0 : _b.blur());
};
return {
submitRef,
inputRef,
fields,
data,
errors,
submitting,
handleChange,
handleSubmit
};
};
exports.useGiftCardForm = useGiftCardForm;