Skip to content

Instantly share code, notes, and snippets.

@KirdesMF
Last active August 17, 2022 22:15
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save KirdesMF/0fa24ce230c517772abbb3052ca9b59d to your computer and use it in GitHub Desktop.
Save KirdesMF/0fa24ce230c517772abbb3052ca9b59d to your computer and use it in GitHub Desktop.
React Hooks useForm
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