-
Notifications
You must be signed in to change notification settings - Fork 1
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
1 changed file
with
33 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; |