Skip to content

Instantly share code, notes, and snippets.

@nmquebb
Created January 29, 2021 23:51
Show Gist options
  • Select an option

  • Save nmquebb/5a0c467babffc3f05884c5811757ec13 to your computer and use it in GitHub Desktop.

Select an option

Save nmquebb/5a0c467babffc3f05884c5811757ec13 to your computer and use it in GitHub Desktop.
useForm
import { ChangeEvent, useState } from 'react';
type InputEvent = ChangeEvent<HTMLInputElement | HTMLSelectElement>;
type BindValueType = (e: InputEvent) => void;
export type BindInputType<T> = (
name: keyof T
) => {
name: typeof name;
value: T[typeof name];
onChange: BindValueType;
};
export type SetValueType<T> = (key: keyof T, value: unknown) => void;
type ErrorsObject<T> = Partial<Record<keyof T, string>>;
type UseFormFns<T> = {
setValue: SetValueType<T>;
bindInput: BindInputType<T>;
bindValue: BindValueType;
values: T;
errors: ErrorsObject<T>;
setErrors(errors: ErrorsObject<T>): void;
setValues(newValues: Partial<Record<keyof T, unknown>>): void;
};
export const useForm = <T>(initialState: T): UseFormFns<T> => {
const [errors, setErrors] = useState<ErrorsObject<T>>({});
const [values, setValues] = useState<T>(initialState);
function bindInput(name: keyof T) {
return {
name,
value: values[name],
onChange: bindValue,
};
}
function bindValue(e: InputEvent) {
setValues({
...values,
[e.currentTarget.name]: e.currentTarget.value,
});
}
function setValue(key: keyof T, value: unknown) {
setValues({ ...values, [key]: value });
}
return {
setValue,
bindInput,
bindValue,
values,
errors,
setErrors,
setValues(newValues) {
setValues({ ...values, ...newValues });
},
};
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment