@open-tender/utils
Version:
A library of utils for use with Open Tender applications that utilize our cloud-based Order API.
98 lines (97 loc) • 3.59 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.useSignInForm = void 0;
const tslib_1 = require("tslib");
const utils_1 = require("../utils");
const react_1 = require("react");
const useSignInForm = (email, loading, error, login, includeRecaptcha, callback) => {
const submitRef = (0, react_1.useRef)(null);
const inputRef = (0, react_1.useRef)(null);
const recaptchaRef = (0, react_1.useRef)(null);
const [data, setData] = (0, react_1.useState)({ email, password: '' });
const [errors, setErrors] = (0, react_1.useState)({});
const isSubmitting = (0, react_1.useRef)(false);
const fields = [
{
label: 'Email',
name: 'email',
type: 'email',
required: true,
disabled: true
},
{
label: 'Password',
name: 'password',
type: 'password',
required: true,
autoComplete: 'new-password'
}
];
(0, react_1.useEffect)(() => {
if (email) {
setData(d => (Object.assign(Object.assign({}, d), { email })));
}
}, [email]);
(0, react_1.useEffect)(() => {
if (loading === 'idle' && isSubmitting.current) {
isSubmitting.current = false;
if (error) {
if (recaptchaRef.current)
recaptchaRef.current.reset();
setErrors((0, utils_1.makeFormErrors)(error));
}
else if (callback) {
callback();
}
}
}, [loading, error, callback]);
const handleChange = (name, value) => {
setData(Object.assign(Object.assign({}, data), { [name]: value }));
};
const handleSubmit = (evt) => tslib_1.__awaiter(void 0, void 0, void 0, function* () {
var _a, _b, _c, _d, _e;
evt === null || evt === void 0 ? void 0 : evt.preventDefault();
const { password } = data;
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) {
isSubmitting.current = false;
setErrors({
form: 'Please complete the recaptcha before submitting'
});
}
else {
login(data.email || email, password, token);
isSubmitting.current = true;
}
}
catch (err) {
isSubmitting.current = false;
setErrors({
form: 'Please complete the recaptcha before submitting'
});
}
}
else {
login(data.email || email, password);
isSubmitting.current = true;
}
((_d = submitRef.current) === null || _d === void 0 ? void 0 : _d.blur) && ((_e = submitRef.current) === null || _e === void 0 ? void 0 : _e.blur());
});
return {
submitRef,
inputRef,
recaptchaRef,
fields,
data,
errors,
submitting: isSubmitting.current,
handleChange,
handleSubmit
};
};
exports.useSignInForm = useSignInForm;