Created
March 8, 2020 03:10
-
-
Save jucian0/dd08f02d4d059b94249930c8e5d4929b to your computer and use it in GitHub Desktop.
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, useEffect, useCallback } from 'react' | |
import { ValidationError } from "yup" | |
const useValidation = (values, schema) => { | |
const [errors, setErrors] = useState({}) | |
const [isValid, setIsValid] = useState(false) | |
const validate = useCallback(async () => { | |
try { | |
await schema.validate(values, { abortEarly: false }) | |
setErrors({}) | |
setIsValid(true) | |
} catch (e) { | |
if (e instanceof ValidationError) { | |
const errors = {} | |
e.inner.forEach((key) => { | |
errors[key.path] = key.message | |
}) | |
setErrors(errors) | |
setIsValid(false) | |
} | |
} | |
}, [schema, values]) | |
useEffect(() => { | |
validate() | |
}, [validate]) | |
return { errors, isValid } | |
} | |
export default useValidation | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment