UNPKG

@open-tender/utils

Version:

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

74 lines (73 loc) 2.64 kB
import { useState, useEffect, useRef } from 'react'; import { makeFormErrors } from '../utils'; export const useResetPasswordForm = (loading, error, reset, resetToken) => { const submitRef = useRef(null); const inputRef = useRef(null); const [data, setData] = useState({}); const [errors, setErrors] = useState({}); const [submitting, setSubmitting] = useState(false); const fields = [ { label: 'New Password', name: 'new_password', type: 'password', required: true }, { label: 'Confirm Password', name: 'confirm', type: 'password', required: true } ]; useEffect(() => { setData({}); setErrors({}); return () => { setData({}); setErrors({}); }; }, []); 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, _c, _d, _e, _f; evt === null || evt === void 0 ? void 0 : evt.preventDefault(); const { new_password, confirm } = data; if (!new_password || new_password.length < 8) { setErrors({ new_password: 'Must be at least 8 characters' }); ((_a = inputRef.current) === null || _a === void 0 ? void 0 : _a.focus) && ((_b = inputRef.current) === null || _b === void 0 ? void 0 : _b.focus()); } else if (new_password !== confirm) { setErrors({ confirm: 'Passwords do not match' }); ((_c = inputRef.current) === null || _c === void 0 ? void 0 : _c.focus) && ((_d = inputRef.current) === null || _d === void 0 ? void 0 : _d.focus()); } else { setErrors({}); setSubmitting(true); reset(new_password, resetToken); } ((_e = submitRef.current) === null || _e === void 0 ? void 0 : _e.blur) && ((_f = submitRef.current) === null || _f === void 0 ? void 0 : _f.blur()); }; return { submitRef, inputRef, fields, data, errors, submitting, handleChange, handleSubmit }; };