Created
September 14, 2020 21:21
-
-
Save aberba/106668f8a639549a05fe99dc642cf294 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, useRef } from "react"; | |
export default function useForm({ | |
callback, | |
validate, | |
defaultValues = {}, | |
defaultErrors = {} | |
}) { | |
const [values, setValues] = useState({}); | |
const [errors, setErrors] = useState({}); | |
useEffect(() => { | |
setErrors(errors => ({ ...errors, ...defaultErrors })); | |
setValues(values => ({ ...values, ...defaultValues })); | |
}, []) | |
function onChange(event) { | |
// e.persist(); | |
setErrors({ ...errors, [event.target.name]: "" }); | |
setValues({ ...values, [event.target.name]: event.target.value }); | |
} | |
function onFocus(event) { | |
console.warn("onFocus is deprecated") | |
} | |
function onSubmit(event) { | |
if (event) event.preventDefault(); | |
// console.log(validate(values)); | |
// console.log(Object.keys(validate(values))); | |
if (Object.keys(validate(values)).length === 0) { | |
callback(values); | |
setErrors({}); | |
} else { | |
setErrors(validate(values)); | |
} | |
} | |
function resetValues() { | |
setValues(defaultValues); | |
} | |
function resetErrors() { | |
setErrors({}); | |
} | |
function setAllValues(v) { | |
console.log("setAllValues", v); | |
setValues(vals => ({ ...vals, ...v })); | |
console.log("current", { values }); | |
} | |
function setAllErrors(e) { | |
setErrors(errs => ({ ...errs, ...e })); | |
} | |
return { | |
errors, | |
values, | |
onFocus, | |
onChange, | |
onSubmit, | |
resetValues, | |
resetErrors, | |
setValues: setAllValues, | |
setErrors: setAllErrors | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment