-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathuseForm.js
45 lines (37 loc) · 1.1 KB
/
useForm.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
import React, { useState,useEffect } from 'react'
const useForm = (stateInicial,validar,fn) => {
const [valores, setValores] = useState(stateInicial);
const [errores, setErrores] = useState({})
const [submitForm, setSubmitForm] = useState(false)
useEffect(() => {
if(submitForm){
const noErrores=Object.keys(errores).length===0;
if(noErrores){
fn();
}
setSubmitForm(false)
}
}, [errores])
//funcion que se ejecuta cuando el usuario escibre algo
const handleChange=(e)=>{
setValores({
...valores,
[e.target.name]:e.target.value
})
}
//funcion que se ejecuta cunado el usuario hace submit
const handleSubmit=(e)=>{
e.preventDefault();
const erroresValidacion=validar(valores)
setErrores(erroresValidacion)
setSubmitForm(true)
}
return {
valores,
errores,
submitForm,
handleSubmit,
handleChange
}
}
export default useForm