UNPKG

@open-tender/utils

Version:

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

57 lines (56 loc) 1.92 kB
import { useState, useEffect, useRef } from 'react'; import { makeFormErrors } from '../utils'; export const useGuestForm = (email, loading, error, checkGuest) => { const submitRef = useRef(null); const inputRef = useRef(null); const [data, setData] = useState({ email }); const [errors, setErrors] = useState({}); const [submitting, setSubmitting] = useState(false); const fields = [ { label: 'Email', name: 'email', type: 'email' } ]; useEffect(() => { var _a, _b; if (loading === 'idle') { setSubmitting(false); if (error) { const errs = makeFormErrors(error); if (errs.form === 'Unknown 500 error') { errs.form = 'Invalid email address. Please try again.'; } setErrors(errs); ((_a = inputRef.current) === null || _a === void 0 ? void 0 : _a.focus) && ((_b = inputRef.current) === null || _b === void 0 ? void 0 : _b.focus()); } } }, [loading, error]); useEffect(() => { if (email && data.email === undefined) { setData({ email }); } }, [email, data.email]); const handleChange = (name, value) => { setData(Object.assign(Object.assign({}, data), { [name]: value })); }; const handleSubmit = (evt) => { var _a, _b; evt === null || evt === void 0 ? void 0 : evt.preventDefault(); setSubmitting(true); if (data.email) checkGuest(data.email); ((_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 }; };