I'm having some trouble with react-bootstrap
(or more likely this is a problem with JavaScript
).
I'm using a select with dynamically loaded content. Selecting some element updates the id
hook. But if I don't select anything (for example if here is only one element in the list) id
hook doesn't get updated. What is the best solution to update hook with actual value of select even if it hasn't been touched by user?
I'm thinking of manually launching onChange
event after the form is loaded or adding a default empty disabled option
to my select
.
Any suggestions?
Here is my code:
const [categories, setCategories] = useState([]);
const [id, setId] = useState(0);
useEffect(() => {
fetchData();
}, []);
async function fetchData() {
try {
const data=await getAll();
setCategories(data)
} catch (e) {
console.error(e);
}
}
export interface Category{
id:number,
name:string
}
<Form.Control as="select" onChange={(e) => setId(parseInt(e.target.value))}>
{categories.map((category: Category) => {
return <option value={category.id}>{category.name}</option>;
})}
</Form.Control>