@open-tender/utils
Version:
A library of utils for use with Open Tender applications that utilize our cloud-based Order API.
94 lines (93 loc) • 3.35 kB
JavaScript
import { __awaiter } from "tslib";
import { makeFormErrors } from '../utils';
import { useState, useEffect, useRef } from 'react';
export const useSignInForm = (email, loading, error, login, includeRecaptcha, callback) => {
const submitRef = useRef(null);
const inputRef = useRef(null);
const recaptchaRef = useRef(null);
const [data, setData] = useState({ email, password: '' });
const [errors, setErrors] = useState({});
const isSubmitting = 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'
}
];
useEffect(() => {
if (email) {
setData(d => (Object.assign(Object.assign({}, d), { email })));
}
}, [email]);
useEffect(() => {
if (loading === 'idle' && isSubmitting.current) {
isSubmitting.current = false;
if (error) {
if (recaptchaRef.current)
recaptchaRef.current.reset();
setErrors(makeFormErrors(error));
}
else if (callback) {
callback();
}
}
}, [loading, error, callback]);
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 { 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
};
};