UNPKG

@open-tender/utils

Version:

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

90 lines (89 loc) 2.95 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.useGuestCheckoutForm = void 0; const react_1 = require("react"); const utils_1 = require("../utils"); const initialData = { first_name: '', last_name: '', email: '', phone: '' }; const useGuestCheckoutForm = (guest, loading, error, guestErrors, submit) => { const submitRef = (0, react_1.useRef)(null); const inputRef = (0, react_1.useRef)(null); const initData = Object.assign(Object.assign({}, initialData), guest); const [data, setData] = (0, react_1.useState)(initData); const [errors, setErrors] = (0, react_1.useState)({}); const [submitting, setSubmitting] = (0, react_1.useState)(false); const disabled = (0, utils_1.checkEmpty)(data); const fields = [ { label: 'First Name', name: 'first_name', type: 'text', required: true }, { label: 'Last Name', name: 'last_name', type: 'text', required: true }, { label: 'Email', name: 'email', type: 'email', required: true }, { label: 'Phone', name: 'phone', type: 'tel', required: true } ]; const handleChange = (name, value) => { const val = name === 'phone' ? (0, utils_1.makePhone)(value) : value; setData(Object.assign(Object.assign({}, data), { [name]: val })); }; const handleSubmit = (evt) => { var _a, _b; evt === null || evt === void 0 ? void 0 : evt.preventDefault(); if (!disabled) { setErrors({}); setSubmitting(true); submit(data); ((_a = submitRef.current) === null || _a === void 0 ? void 0 : _a.blur) && ((_b = submitRef.current) === null || _b === void 0 ? void 0 : _b.blur()); } }; (0, react_1.useEffect)(() => { var _a, _b; if (loading === 'idle') { setSubmitting(false); if (error) { const errs = (0, utils_1.makeFormErrors)(error); errs.form = 'There are one or more errors below'; setErrors(errs); ((_a = inputRef.current) === null || _a === void 0 ? void 0 : _a.focus) && ((_b = inputRef.current) === null || _b === void 0 ? void 0 : _b.focus()); } else if (guestErrors) { setErrors(guestErrors); } } }, [loading, error, guestErrors]); (0, react_1.useEffect)(() => { return () => { setData(initialData); setErrors({}); setSubmitting(false); }; }, []); return { submitRef, inputRef, fields, data, errors, disabled, submitting, handleChange, handleSubmit }; }; exports.useGuestCheckoutForm = useGuestCheckoutForm;