Skip to content

Instantly share code, notes, and snippets.

@fhugoduarte
Created September 26, 2020 14:08
Show Gist options
  • Star 6 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save fhugoduarte/5042a0bf847248d397035db44fc651f4 to your computer and use it in GitHub Desktop.
Save fhugoduarte/5042a0bf847248d397035db44fc651f4 to your computer and use it in GitHub Desktop.
A validation hook to unform 2.0
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