Add Paul's Toolbox Contents
This commit is contained in:
@@ -0,0 +1,95 @@
|
||||
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;
|
||||
Reference in New Issue
Block a user