working on an issue with the react-select AsyncSelect ponent that loads options from an API.But I can't pass the information to React-Hook Form through the controller.AsyncSelect works perfectly. The data goes back well in my "SelelectedValue" state. Can anyone help me ?
const [inputValue, setValue] = useState('');
const [selectedValue, setSelectedValue] = useState(null);
// handle input change event
const handleInputChange = value => {
setValue(value);
};
// handle selection
const handleChange = value => {
setSelectedValue(value);
}
const loadOptions = async (inputValue, callback) => {
const response = await fetch(`APIurl`);
const json = await response.json();
const object = json.records;
callback(object.map(i => ({ label: `${i.fields.firstName} - ${i.fields.lasName} , value: i.fields.firstName })))
}
<Controller
name="pany"
control={control}
rules={{ required: true }}
render={({ field: { onChange, value } }) => (
<AsyncSelect
isClearable
value={selectedValue}
placeholder={'Your information'}
loadOptions={loadOptions}
onInputChange={handleInputChange}
onChange={handleChange}
styles={customStyles}
/>)}
/>
working on an issue with the react-select AsyncSelect ponent that loads options from an API.But I can't pass the information to React-Hook Form through the controller.AsyncSelect works perfectly. The data goes back well in my "SelelectedValue" state. Can anyone help me ?
const [inputValue, setValue] = useState('');
const [selectedValue, setSelectedValue] = useState(null);
// handle input change event
const handleInputChange = value => {
setValue(value);
};
// handle selection
const handleChange = value => {
setSelectedValue(value);
}
const loadOptions = async (inputValue, callback) => {
const response = await fetch(`APIurl`);
const json = await response.json();
const object = json.records;
callback(object.map(i => ({ label: `${i.fields.firstName} - ${i.fields.lasName} , value: i.fields.firstName })))
}
<Controller
name="pany"
control={control}
rules={{ required: true }}
render={({ field: { onChange, value } }) => (
<AsyncSelect
isClearable
value={selectedValue}
placeholder={'Your information'}
loadOptions={loadOptions}
onInputChange={handleInputChange}
onChange={handleChange}
styles={customStyles}
/>)}
/>
Share
Improve this question
asked Jul 11, 2021 at 14:52
heliowxheliowx
431 silver badge3 bronze badges
1 Answer
Reset to default 3react-hook-form
manages some mon event and state (like value, onChange, onBlur etc.) for you so there is no need to define your own state in most case except onInputChange
in AsyncSelect
.
You can try to select the option and submit the form.
<Controller
name="pany"
control={control}
rules={{ required: true }}
render={({ field }) => (
<AsyncSelect
{...field}
isClearable
defaultOptions
placeholder={"Your information"}
loadOptions={loadOptions}
onInputChange={handleInputChange}
// styles={customStyles}
/>
)}
/>
Here is the codesandbox
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745600256a4635359.html
评论列表(0条)