2023-03-29 18:14:41 -07:00
|
|
|
import { useEffect, useState } from 'react';
|
|
|
|
|
2023-03-29 18:29:35 -07:00
|
|
|
/**
|
|
|
|
* Returns props for `<input type="text">`.
|
|
|
|
* If `initialValue` changes from undefined to a string, it will set the value.
|
|
|
|
*/
|
2023-03-29 18:14:41 -07:00
|
|
|
function useTextField(initialValue: string | undefined) {
|
|
|
|
const [value, setValue] = useState(initialValue);
|
|
|
|
const hasInitialValue = typeof initialValue === 'string';
|
|
|
|
|
|
|
|
const onChange: React.ChangeEventHandler<HTMLInputElement | HTMLTextAreaElement> = (e) => {
|
|
|
|
setValue(e.target.value);
|
|
|
|
};
|
|
|
|
|
|
|
|
useEffect(() => {
|
|
|
|
if (hasInitialValue) {
|
|
|
|
setValue(initialValue);
|
|
|
|
}
|
|
|
|
}, [hasInitialValue]);
|
|
|
|
|
|
|
|
return {
|
2023-03-29 18:29:35 -07:00
|
|
|
value: value || '',
|
2023-03-29 18:14:41 -07:00
|
|
|
onChange,
|
|
|
|
};
|
|
|
|
}
|
|
|
|
|
|
|
|
export { useTextField };
|