Skip to content

Instantly share code, notes, and snippets.

@aberba
Created September 14, 2020 21:21
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 aberba/106668f8a639549a05fe99dc642cf294 to your computer and use it in GitHub Desktop.
Save aberba/106668f8a639549a05fe99dc642cf294 to your computer and use it in GitHub Desktop.
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