Created
September 26, 2020 14:08
-
-
Save fhugoduarte/5042a0bf847248d397035db44fc651f4 to your computer and use it in GitHub Desktop.
A validation hook to unform 2.0
This file contains hidden or 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 { FormHandles, SubmitHandler } from '@unform/core'; | |
import { RefObject, useCallback, useState } from 'react'; | |
import { ObjectSchema, ValidationError } from 'yup'; | |
type Hook = <T>( | |
args: Props<T>, | |
) => { | |
validating: boolean; | |
handleSubmit: SubmitHandler<T>; | |
}; | |
interface Props<T> { | |
formRef: RefObject<FormHandles>; | |
schema: ObjectSchema; | |
extraData?: any; | |
onSuccess: (data: T) => void; | |
} | |
export const useValidateForm: Hook = ({ | |
formRef, | |
schema, | |
onSuccess, | |
extraData = [], | |
}) => { | |
const [validating, setValidating] = useState(false); | |
const extraDataArray = Array.isArray(extraData) ? extraData : [extraData]; | |
const success = useCallback(onSuccess, extraDataArray); | |
const handleSubmit = useCallback( | |
async formData => { | |
formRef.current?.setErrors({}); | |
try { | |
setValidating(true); | |
const data: any = await schema.validate(formData, { | |
abortEarly: false, | |
}); | |
success(data); | |
} catch (err) { | |
const validationErrors: any = {}; | |
if (err instanceof ValidationError) { | |
err.inner.forEach(error => { | |
validationErrors[error.path] = error.message; | |
}); | |
formRef.current?.setErrors(validationErrors); | |
} | |
} finally { | |
setValidating(false); | |
} | |
}, | |
[formRef, schema, success], | |
); | |
return { | |
handleSubmit, | |
validating, | |
}; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment