Last active
August 17, 2022 22:15
-
-
Save KirdesMF/0fa24ce230c517772abbb3052ca9b59d to your computer and use it in GitHub Desktop.
React Hooks useForm
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { useState } from 'react'; | |
import { checkErrorsInput, checkErrorsForm } from 'utils/checkForm'; | |
const useForm = ( | |
initState = { | |
errors: {}, | |
values: {}, | |
isSubmitted: false, | |
isFormValid: false, | |
} | |
) => { | |
const [state, setState] = useState(initState); | |
const { hasNoErrors, finalErrors } = checkErrorsForm(state.values); | |
// check value while typing | |
const handleChange = (event) => { | |
const { name, value } = event.target; | |
setState((prevState) => ({ | |
...prevState, | |
values: { | |
...prevState.values, | |
[name]: value, | |
}, | |
errors: { | |
...prevState.errors, | |
...checkErrorsInput(name, value), | |
}, | |
})); | |
}; | |
// check value on Blur | |
const handleTouched = (event) => { | |
const { name, value } = event.target; | |
setState((prevState) => ({ | |
...prevState, | |
errors: { | |
...prevState.errors, | |
...checkErrorsInput(name, value), | |
}, | |
})); | |
}; | |
const handleSubmit = (event) => { | |
event.preventDefault(); | |
// store final values and add a date | |
const finalValues = { | |
...state.values, | |
date: new Date().toLocaleDateString('fr-FR'), | |
}; | |
// send data if there is no errors | |
hasNoErrors | |
? setState((prevState) => ({ | |
...prevState, | |
values: finalValues, | |
isSubmitted: true, | |
isFormValid: true, | |
})) | |
: setState((prevState) => ({ | |
...prevState, | |
errors: { | |
...prevState.errors, | |
...finalErrors, | |
}, | |
isFormValid: false, | |
isSubmitted: true, | |
})); | |
}; | |
// optional pop up | |
const handleSubmitted = () => { | |
state.isFormValid | |
? setState((prevState) => ({ | |
...prevState, | |
...initState, | |
isSubmitted: false, | |
isFormValid: false, | |
})) | |
: setState((prevState) => ({ | |
...prevState, | |
errors: { | |
...prevState.errors, | |
...finalErrors, | |
}, | |
isSubmitted: false, | |
isFormValid: false, | |
})); | |
}; | |
return { | |
handleChange, | |
handleTouched, | |
handleSubmit, | |
handleSubmitted, | |
state, | |
}; | |
}; | |
export default useForm; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment