/
useChoice.ts
44 lines (40 loc) · 1.36 KB
/
useChoice.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
import type { Dispatch, SetStateAction } from "react";
import { useCallback, useState } from "react";
type InputElement = HTMLInputElement | HTMLSelectElement;
type ChangeEventHandler<E extends InputElement> = React.ChangeEventHandler<E>;
type DefaultValue =
| string
| number
| readonly string[]
| (() => string | number | readonly string[]);
type SetValue<T extends DefaultValue> = Dispatch<SetStateAction<T>>;
/**
* This hook can be used to control the state of a radio group or a select
* element.
*
* @param defaultValue - The default value. If you want the user to specifically
* choose a value, set this to the empty string.
* @param onChange - An optional change event handler to also call when the
* change event is triggered.
* @returns a list containing the current value, a change event handler, and
* then a manual value setter.
*/
export function useChoice<
T extends DefaultValue = DefaultValue,
E extends InputElement = InputElement
>(
defaultValue: T,
onChange?: ChangeEventHandler<E>
): readonly [T, ChangeEventHandler<E>, SetValue<T>] {
const [value, setValue] = useState<T>(defaultValue);
const handleChange = useCallback<ChangeEventHandler<E>>(
(event) => {
if (onChange) {
onChange(event);
}
setValue(event.currentTarget.value as T);
},
[onChange]
);
return [value, handleChange, setValue];
}