Skip to content

Instantly share code, notes, and snippets.

@itsaalexk
Forked from Klerith/useForm.js
Created February 14, 2023 08:06
Show Gist options
  • Save itsaalexk/d4e9431f33fe895812dd5e06655f61a3 to your computer and use it in GitHub Desktop.
Save itsaalexk/d4e9431f33fe895812dd5e06655f61a3 to your computer and use it in GitHub Desktop.
useForm con Validaciones
import { useEffect, useMemo, useState } from 'react';
export const useForm = ( initialForm = {}, formValidations = {}) => {
const [ formState, setFormState ] = useState( initialForm );
const [ formValidation, setFormValidation ] = useState({});
useEffect(() => {
createValidators();
}, [ formState ])
useEffect(() => {
setFormState( initialForm );
}, [ initialForm ])
const isFormValid = useMemo( () => {
for (const formValue of Object.keys( formValidation )) {
if ( formValidation[formValue] !== null ) return false;
}
return true;
}, [ formValidation ])
const onInputChange = ({ target }) => {
const { name, value } = target;
setFormState({
...formState,
[ name ]: value
});
}
const onResetForm = () => {
setFormState( initialForm );
}
const createValidators = () => {
const formCheckedValues = {};
for (const formField of Object.keys( formValidations )) {
const [ fn, errorMessage ] = formValidations[formField];
formCheckedValues[`${ formField }Valid`] = fn( formState[formField] ) ? null : errorMessage;
}
setFormValidation( formCheckedValues );
}
return {
...formState,
formState,
onInputChange,
onResetForm,
...formValidation,
isFormValid
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment