custom hooks for password input

Solutions on MaxInterview for custom hooks for password input by the best coders in the world

showing results for - "custom hooks for password input"
Luca
08 Jul 2018
1function useForm(initialValues, validateForm) {
2  if (!initialValues) {
3    throw Error('Initial values are required')
4  }
5
6  const values = {}
7  const valuesWithSetters = {}
8  const [errors, setErrors ] = useState({})
9  const keys =  Object.keys(initialValues)
10
11  for (let i = 0, l = keys.length; i < l; i ++) {
12    const key = keys[i]
13    const [val, setVal] = useInputValue(initialValues[key])
14    const setValWrapper = (...pars) => {
15      if (errors[key]) {
16        const er = {...errors}
17        delete er[key]
18        setErrors(er)
19      }
20      setVal(...pars)
21    }
22    valuesWithSetters[key] = [val, setValWrapper, () => errors[key]]
23    values[key] = val
24  }
25
26  function validate() {
27    const errorObject = {}
28    validateForm(errorObject, values)
29    setErrors(errorObject)
30    return Object.keys(errorObject).length < 1
31  }
32
33  return  [valuesWithSetters, validate, errors, values ]
34}
35