Home-Toolbox-Plugin/hooks/useForm.ts

96 lines
2.1 KiB
TypeScript

import { useEffect, useRef, type FormEvent } from "react";
type Values = Record<string, string | number>;
interface Props {
initialValues?: Values;
onSubmit?: (values: Values) => void;
}
type a = (values: Values) => void;
interface UseFormReturns {
getValue: () => Values;
setValue: (name: string, value: string | number) => void;
setValues: (values: Values) => void;
bindInput: (name: string) => any;
onSubmit: (a: a) => (ev: FormEvent) => void;
}
function useForm({ initialValues }: Props) {
const formRef = useRef<HTMLFormElement>();
const inputs = useRef({});
const values = useRef({ ...initialValues });
const inst = useRef<UseFormReturns>();
if (!inst.current) {
const getValue = () => {
return values.current;
}
const setValue = (name, value) => {
console.log(inputs.current[name]);
if (inputs.current[name]) {
values.current[name] = value;
inputs.current[name].value = value;
}
}
const setValues = (values: Values) => {
Object.keys(values).forEach((key) => {
setValue(key, values[key]);
});
}
const bindInput = (name: string) => {
console.log('bindinput')
return {
name,
id: name,
ref: (target) => {
console.log('ref', target);
if (target) {
inputs.current[name] = target;
}
return undefined;
},
defaultValue: initialValues[name],
onChange: (ev) => {
values.current[ev.target.name] = ev.target.value;
},
}
}
const onSubmit = (fn) => (ev: SubmitEvent) => {
ev.preventDefault();
fn(getValue());
}
inst.current = {
getValue,
setValue,
setValues,
bindInput,
onSubmit,
};
}
useEffect(() => {
console.log('form', formRef.current);
// formRef.current.onsubmit = (ev: SubmitEvent) => {
// ev.preventDefault();
// console.log(t.current?.getValue());
// console.log(inputs);
// }
}, []);
return inst.current;
}
export default useForm;