'One dropdown overwriting another's value
I'm making a page with javascript react and formik and I have two dropdowns in one form, I got them to work but now that I'm using both of them, when I choose a value with one the other's value resets. Don't know how to word this better so I'll add a gif of what happens:
These are my drop down menus (both identical just taking values from a different object).
<Field
as="select"
className="custom-select d-block w-100"
name="fk_room"
required
>
<option></option>
{this.state.doctors.map((doctors) => (
<option value={doctors.surname} selected>
{" "}
{doctors.surname}
</option>
))}
</Field>
I have a sneaking suspicion it's likely to do with me setting the state twice
componentDidMount() {
userService.getAllRooms().then((result) => {
this.setState({
rooms: result.map(({ name }) => name),
});
});
userService.getAllEmployees().then((result) => {
this.setState({
doctors: result.map(o => ({name: o.name, surname: o.surname, specialization: o.specialization})),
});
});
}
even though with console.log it looks like I get the values correctly, I assume something funky is going on since every dropdown click calls the componentDidMount again (I think). Has anyone dealt with a similar issue? Does it have to do with me setting the state twice or I need to somehow save the value from the dropdowns? (It worked fine with just 1 dropdown menu where I called the state once). Sorry if this is complete novice territory I am very inexperienced in javascript and react. P.S. the dropdowns are completely independent, all the guides I found online were about dependent dropdown menus but this is not the final result I want, they both should never change from the initial call to fill the objects.
Solution 1:[1]
componentDidMount() {
userService.getAllRooms().then((result) => {
this.setState((state)=>({
...state,
rooms: result.map(({ name }) => name),
}));
});
userService.getAllEmployees().then((result) => {
this.setState((state)=>({
...state,
doctors: result.map(o => ({name: o.name, surname: o.surname, specialization: o.specialization})),
});
}));
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | KeyvanKh |

