I have two dropdowns, the values of the second dropdown should be updated based on the state of the first dropdown.
Although the code seems to work, I get warnings for out-of-range value. How can I improve this code so that the warnings disappear?
The full component in case that's preferred.
const MyForm = () => {
const [state1, setState1] = useState(list1[0]);
const [state2, setState2] = useState(list2[0]);
return (
<>
<FormControl fullWidth sx={{ marginY: "16px" }}>
<InputLabel>List 1</InputLabel>
<Select
label="List 1"
value={state1.code}
onChange={(e) => {
const tmpState1 = list1.find(
(item) => item.code === e.target.value
);
setState1(tmpState1);
}}
>
{list1.map((item) => {
return (
<MenuItem value={item.code} key={item.name}>
{item.name}
</MenuItem>
);
})}
<MenuItem value={""}>All</MenuItem>
</Select>
</FormControl>
<FormControl fullWidth sx={{ marginY: "16px" }}>
<InputLabel>List 2</InputLabel>
<Select
label="List 2"
value={state2.name}
onChange={(e) => {
const tmpState2 = list2.find(
(item) => item.name === e.target.value
);
console.log(tmpState2);
setState2(tmpState2);
}}
>
{list2
.filter((item) => item.code === state1.code)
.map((item) => {
return (
<MenuItem value={item.name} key={item.name}>
{item.name}
</MenuItem>
);
})}
</Select>
</FormControl>
</>
);
};
export default MyForm;
The problem was that when the variable state1 get's updated, the value of the second dropdown isn't among the list of updated <MenuItem>s. Thus it throws a warning.
A simple fix is to update the value in the second dropdown when the state1 changes:
//...
<FormControl fullWidth sx={{ marginY: "16px" }}>
<InputLabel>List 1</InputLabel>
<Select
label="List 1"
value={state1.code}
onChange={(e) => {
const tmpState1 = list1.find(
(item) => item.code === e.target.value);
{/* this is the fix */}
setState2(list2.find((item) => item.code === tmpState1.code));
setState1(tmpState1);
}}
>
{list1.map((item) => {
return (
<MenuItem value={item.code} key={item.name}>
{item.name}
</MenuItem>
);
})}
<MenuItem value={""}>All</MenuItem>
</Select>
</FormControl>
//...