UNPKG

@open-tender/utils

Version:

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

55 lines (54 loc) 1.95 kB
import { useRef, useState, useEffect } from 'react'; import { makeFormErrors } from '../utils'; const initState = { first_name: '', last_name: '' }; export const useCartGuestForm = (loading, error, cartId, joinCart) => { const submitRef = useRef(null); const inputRef = useRef(null); const [data, setData] = useState(Object.assign(Object.assign({}, initState), { cart_id: cartId })); const [submitting, setSubmitting] = useState(false); const [errors, setErrors] = useState({}); const fields = [ { label: 'First Name', name: 'first_name', type: 'text', required: true }, { label: 'Last Name', name: 'last_name', type: 'text', required: true } ]; useEffect(() => { return () => { setData(Object.assign(Object.assign({}, initState), { cart_id: cartId })); setErrors({}); }; }, [cartId]); 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) => { setData(Object.assign(Object.assign({}, data), { [name]: value })); }; const handleSubmit = (evt) => { var _a, _b; evt === null || evt === void 0 ? void 0 : evt.preventDefault(); setErrors({}); setSubmitting(true); joinCart(data); ((_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, data, errors, submitting, fields, handleChange, handleSubmit }; };