UNPKG

@open-tender/utils

Version:

A library of utils for use with Open Tender applications that utilize our cloud-based Order API.

97 lines (96 loc) 3.42 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.useLoginForm = void 0; const tslib_1 = require("tslib"); const react_1 = require("react"); const utils_1 = require("../utils"); const useLoginForm = (loading, error, login, includeRecaptcha, callback, showPassword = true, requiredEmail, getRecaptchaToken) => { const submitRef = (0, react_1.useRef)(null); const inputRef = (0, react_1.useRef)(null); const [data, setData] = (0, react_1.useState)({ email: requiredEmail || '', password: '' }); const [errors, setErrors] = (0, react_1.useState)({}); const [submitting, setSubmitting] = (0, react_1.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)); (0, react_1.useEffect)(() => { var _a, _b; if (loading === 'idle' && submitting) { setSubmitting(false); if (error) { setErrors((0, utils_1.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) => tslib_1.__awaiter(void 0, void 0, void 0, function* () { var _a, _b; evt === null || evt === void 0 ? void 0 : evt.preventDefault(); const { email, password } = data; if (includeRecaptcha) { try { const token = yield (getRecaptchaToken === null || getRecaptchaToken === void 0 ? void 0 : getRecaptchaToken()); 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); } ((_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.useLoginForm = useLoginForm;