-
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 1 reply
-
Greetings @onasolani, You would need to use the Select as a controlled component, meaning that the selected value is kept in state and passed to the Select as a prop. Since you would not be able to select the default hospital option until your list of hospitals or default id has come back from the api, you would likely want to create a useEffect hook to listen for changes to the options to know how/when to select the correct default value. For example: // assuming we have the id_Hospital passed in as a prop to the component
const { id_Hospital, handleChangeSelect } = props;
const [ hospitalOptions, setHospitalOptions ] = useState([]);
const [ hospitalValue, setHospitalValue ] = useState();
useEffect(() => {
// Async/await function needs to be declared first, then called when used inside useEffect hook
const onMount = async () => {
const resp = await yourApi.getHospitals();
const options = resp.map(x => ({ label: x.nombre, value: x.id.toString() }));
setHospitalOptions(options);
// verify if any of the hospital options match the id and set the select value
if (id_Hospital) {
const value = options.find(x => x.value === id_Hospital);
setHospitalValue(value);
}
};
// Call declared async function
onMount();
}, [ id_Hospital ]);
// onChange returns two parameters
// value: selected option(s)
// actionMeta: object containing information about onChange event which includes the select's `name` prop as a parameter
const onChange = (value, actionMeta) => {
setHospitalValue(value);
handleChangeSelect(value, actionMeta.name);
};
return <Select options={hospitalOptions} value={hospitalValue} {...otherProps} /> Please let me know if you have any other questions, or we can create a codesandbox and work through any other questions you might have |
Beta Was this translation helpful? Give feedback.
Greetings @onasolani,
You would need to use the Select as a controlled component, meaning that the selected value is kept in state and passed to the Select as a prop.
Since you would not be able to select the default hospital option until your list of hospitals or default id has come back from the api, you would likely want to create a useEffect hook to listen for changes to the options to know how/when to select the correct default value.
For example: