Skip to content

Instantly share code, notes, and snippets.

@jucian0
Created March 8, 2020 03:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jucian0/dd08f02d4d059b94249930c8e5d4929b to your computer and use it in GitHub Desktop.
Save jucian0/dd08f02d4d059b94249930c8e5d4929b to your computer and use it in GitHub Desktop.
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