Reputation: 89
I try to use Select Box from MUI All really simple, like in an MUI demo
Just one thing, my default value comes after an API call.
So, I need to 'Update' the default value.
After 5 sec the value of 'age' is updated to 30, but the select box doesn't.
How to fix it?
const [age, setAge] = React.useState<number>();
React.useEffect(() => {
//Emulate API call
setTimeout(() => {
setAge(30);
}, 5000);
}, []);
const handleChange = (event: React.ChangeEvent<{ value: unknown }>) => {
setAge(event.target.value as any);
};
return (
<Box sx={{ minWidth: 120 }}>
<FormControl fullWidth>
<InputLabel id="demo-simple-select-label">Age</InputLabel>
<Select
labelId="demo-simple-select-label"
id="demo-simple-select"
value={age}
label="Age"
onChange={handleChange}
>
<MenuItem value={10}>Ten</MenuItem>
<MenuItem value={20}>Twenty</MenuItem>
<MenuItem value={30}>Thirty</MenuItem>
</Select>
</FormControl>
Current Age: {age}
</Box>
);
code on sandbox: https://codesandbox.io/s/basicselect-material-demo-api-call-7k46b?file=/demo.tsx
Upvotes: 2
Views: 5848
Reputation: 201
You just need to get rid of initial undefined value of age. You can see the error in the console that undefined is out of the options range value.
const [age, setAge] = React.useState<number | ''>('');
Upvotes: 3