Answers for "custom hooks for password input"

0

custom hooks for password input

function useForm(initialValues, validateForm) {
  if (!initialValues) {
    throw Error('Initial values are required')
  }

  const values = {}
  const valuesWithSetters = {}
  const [errors, setErrors ] = useState({})
  const keys =  Object.keys(initialValues)

  for (let i = 0, l = keys.length; i < l; i ++) {
    const key = keys[i]
    const [val, setVal] = useInputValue(initialValues[key])
    const setValWrapper = (...pars) => {
      if (errors[key]) {
        const er = {...errors}
        delete er[key]
        setErrors(er)
      }
      setVal(...pars)
    }
    valuesWithSetters[key] = [val, setValWrapper, () => errors[key]]
    values[key] = val
  }

  function validate() {
    const errorObject = {}
    validateForm(errorObject, values)
    setErrors(errorObject)
    return Object.keys(errorObject).length < 1
  }

  return  [valuesWithSetters, validate, errors, values ]
}
Posted by: Guest on December-09-2020

Code answers related to "custom hooks for password input"

Code answers related to "Javascript"

Browse Popular Code Answers by Language