@open-tender/utils
Version:
A library of utils for use with Open Tender applications that utilize our cloud-based Order API.
54 lines (53 loc) • 1.99 kB
JavaScript
import { useState, useEffect, useRef } from 'react';
import { makeFormErrors } from '../utils';
export const useGiftCardAssignForm = (loading, error, assign, callback) => {
const submitRef = useRef(null);
const inputRef = useRef(null);
const [data, setData] = useState({ card_number: '' });
const [errors, setErrors] = useState({});
const [submitting, setSubmitting] = useState(false);
const fields = [
{
label: 'Gift Card Number',
name: 'card_number',
type: 'text'
}
];
useEffect(() => {
var _a, _b;
if (loading === 'idle') {
setSubmitting(false);
if (error) {
setErrors(makeFormErrors(error));
((_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, _c, _d;
evt === null || evt === void 0 ? void 0 : evt.preventDefault();
const card_number = parseInt(data.card_number);
if (isNaN(card_number)) {
setErrors({ card_number: 'Card numbers must be all digits' });
((_a = inputRef.current) === null || _a === void 0 ? void 0 : _a.focus) && ((_b = inputRef.current) === null || _b === void 0 ? void 0 : _b.focus());
}
else {
setSubmitting(true);
assign(card_number, callback);
((_c = submitRef.current) === null || _c === void 0 ? void 0 : _c.blur) && ((_d = submitRef.current) === null || _d === void 0 ? void 0 : _d.blur());
}
};
return {
submitRef,
inputRef,
fields,
data,
errors,
submitting,
handleChange,
handleSubmit
};
};