Skip to content

Commit

Permalink
feat: Add useInput hook
Browse files Browse the repository at this point in the history
  • Loading branch information
Jun99uu committed Oct 16, 2023
1 parent 0ec0edc commit 938a6bf
Showing 1 changed file with 33 additions and 0 deletions.
33 changes: 33 additions & 0 deletions client/src/hooks/useInput.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
import { ChangeEvent, useState } from 'react';
import { set } from 'lodash';

type UseInputReturnType<T> = {
values: T;
handleChange: (event: ChangeEvent<HTMLInputElement>) => void;
setValue: <K extends keyof T>(path: K, value: T[K]) => void;
};

const useInput = <T extends object>(
initialValues: T,
): UseInputReturnType<T> => {
const [values, setValues] = useState<T>(initialValues);

const handleChange = (event: ChangeEvent<HTMLInputElement>): void => {
const { name, value } = event.target;
const updatedValues = set({ ...values }, name, value);
setValues(updatedValues as T);
};

const setValue = <K extends keyof T>(path: K, value: T[K]): void => {
const updatedValues = set({ ...values }, path as string, value);
setValues(updatedValues as T);
};

return {
values,
handleChange,
setValue,
};
};

export default useInput;

0 comments on commit 938a6bf

Please sign in to comment.