@open-tender/utils
Version:
A library of utils for use with Open Tender applications that utilize our cloud-based Order API.
100 lines (99 loc) • 3.63 kB
JavaScript
import { __awaiter } from "tslib";
import { useState, useEffect, useRef } from 'react';
import { makeFormErrors } from '../utils';
export const useLoginForm = (loading, error, login, includeRecaptcha, callback, showPassword = true, requiredEmail) => {
const submitRef = useRef(null);
const inputRef = useRef(null);
const recaptchaRef = useRef(null);
const [data, setData] = useState({
email: requiredEmail || '',
password: ''
});
const [errors, setErrors] = useState({});
const [submitting, setSubmitting] = useState(false);
const toRemove = [];
if (!showPassword)
toRemove.push('password');
const allFields = [
{
label: 'Email',
name: 'email',
type: 'email',
required: true,
disabled: !!requiredEmail
},
{
label: 'Password',
name: 'password',
type: 'password',
required: true,
autoComplete: 'new-password'
}
];
const fields = allFields.filter(i => !toRemove.includes(i.name));
useEffect(() => {
var _a, _b;
if (loading === 'idle' && submitting) {
setSubmitting(false);
if (error) {
if (recaptchaRef.current)
recaptchaRef.current.reset();
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());
}
else if (callback && submitting) {
callback();
}
}
}, [loading, error, callback, submitting]);
const handleChange = (name, value) => {
setData(Object.assign(Object.assign({}, data), { [name]: value }));
};
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();
const { email, 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) {
setSubmitting(false);
setErrors({
form: 'Please complete the recaptcha before submitting'
});
}
else {
if (email)
login(email, password, token);
setSubmitting(true);
}
}
catch (err) {
setSubmitting(false);
setErrors({
form: 'Please complete the recaptcha before submitting'
});
}
}
else {
if (email)
login(email, password);
setSubmitting(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,
handleChange,
handleSubmit
};
};