UNPKG

@open-tender/utils

Version:

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

80 lines (79 loc) 2.55 kB
import { useState, useEffect, useRef } from 'react'; import { makeFormErrors, makePhone } from '../utils'; export const useAddressForm = (address, loading, error, update, callback) => { const submitRef = useRef(null); const inputRef = useRef(null); const [data, setData] = useState(address); const [errors, setErrors] = useState({}); const [submitting, setSubmitting] = useState(false); const fields = [ { label: 'Company', name: 'company', type: 'text' }, { label: 'Contact Person', name: 'contact', type: 'text' }, { label: 'Contact Phone', name: 'phone', type: 'tel' }, { label: 'Description', name: 'description', type: 'text' }, { label: 'Notes', name: 'notes', type: 'text' }, { label: 'Is Default', name: 'is_default', type: 'checkbox' } ]; useEffect(() => { var _a, _b; if (loading === 'idle') { setSubmitting(false); if (error) { setErrors(makeFormErrors(error)); ((_a = inputRef.current) === null || _a === void 0 ? void 0 : _a.focus) && ((_b = inputRef.current) === null || _b === void 0 ? void 0 : _b.focus()); } } }, [loading, error]); const handleChange = (name, value) => { const inputValue = name === 'phone' ? makePhone((value !== null && value !== void 0 ? value : '')) : value; setData(Object.assign(Object.assign({}, data), { [name]: inputValue })); }; const handleSubmit = (evt) => { var _a, _b; evt === null || evt === void 0 ? void 0 : evt.preventDefault(); setSubmitting(true); const updatedData = Object.assign({}, data); delete updatedData.customer_address_id; delete updatedData.created_at; delete updatedData.last_used_at; const addressId = data.customer_address_id; if (addressId) { update(addressId, updatedData, callback); ((_a = submitRef.current) === null || _a === void 0 ? void 0 : _a.blur) && ((_b = submitRef.current) === null || _b === void 0 ? void 0 : _b.blur()); } }; return { fields, data, errors, submitting, handleChange, handleSubmit, submitRef, inputRef }; };