@ducor/form
Version:
form package
34 lines (33 loc) • 1.3 kB
JavaScript
import { jsx as _jsx } from "react/jsx-runtime";
import { FormProvider, useForm } from "react-hook-form";
import { twMerge } from "tailwind-merge";
import { useEffect } from "react";
export const Form = ({ children, onSubmit, defaultValues, className, errors = {}, method = "get", action = "", errorType = "inline", }) => {
const methods = useForm({
defaultValues,
mode: "onBlur",
});
useEffect(() => {
if (errors) {
Object.keys(errors).forEach((field) => {
methods.setError(field, {
type: "manual",
message: errors[field],
});
});
}
}, [errors, methods.setError]);
const handleSubmit = () => {
if (typeof onSubmit === "function") {
onSubmit({
values: methods.getValues(),
errorType,
});
// methods.reset();
if (Object.keys(methods.formState.errors).length === 0) {
methods.reset();
}
}
};
return (_jsx(FormProvider, Object.assign({}, methods, { children: _jsx("form", { onSubmit: methods.handleSubmit(handleSubmit), method: method, action: action, className: twMerge("space-y-4", className), children: children }) })));
};