UNPKG

@open-tender/utils

Version:

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

66 lines (65 loc) 2.34 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.useOrderFulfillmentForm = void 0; const react_1 = require("react"); const utils_1 = require("../utils"); const initState = { arrival_info: '', has_arrived: false, vehicle_color: '', vehicle_id: '', vehicle_type: '' }; const useOrderFulfillmentForm = (orderId, fulfillment, loading, error, update, settings, showAllFields = false) => { const submitRef = (0, react_1.useRef)(null); const [data, setData] = (0, react_1.useState)(fulfillment || initState); const [errors, setErrors] = (0, react_1.useState)({}); const [submitting, setSubmitting] = (0, react_1.useState)(false); const empty = fulfillment ? Object.values(fulfillment).every(i => !i) : true; const arrivalOnly = !empty && !showAllFields; const hasArrived = data.has_arrived; const allFields = arrivalOnly ? settings.fields.filter(i => i.name.startsWith('arrival')) : settings.fields; const fields = allFields .filter(i => i.name !== 'has_arrived') .map(i => ({ label: i.label, name: i.name, placeholder: i.placeholder, type: 'text', disabled: hasArrived })); (0, react_1.useEffect)(() => { if (loading === 'idle') { setSubmitting(false); if (error) { setErrors((0, utils_1.makeFormErrors)(error)); } } }, [loading, error]); (0, react_1.useEffect)(() => { if (fulfillment) setData(fulfillment); }, [fulfillment]); 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); update(orderId, Object.assign(Object.assign({}, data), { has_arrived: 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, fields, data, errors, submitting, handleChange, handleSubmit }; }; exports.useOrderFulfillmentForm = useOrderFulfillmentForm;