Reputation: 163
So, I have a selection with a dropdown list which has 1 default answer. This is the code for the list:
renderPersonnel = (selectedRelationId: number) => HTML
${this.emptyPersonnelOption(!selectedRelationId)}
${this.personnel.map(
({id, name}) =>
this.personnelSuggestionOption(id, name, selectedRelationId === Number(id)
))}
this.personnel
is being set by the following code:
this.personnel = await fetch(getPersonnelByFunctionUrl(functionId))
.then(response => response.json());
// If the list does not contain the current relation, add the current relation if it exists
if(this.shift.relation != null && !this.personnel.map(personnel => personnel.id).includes(this.shift.relation.id)) {
this.personnel.push(this.shift.relation);
}
The last line will check if the current selected option is a deleted relation (it still exists in the database, but will not be included when the personnel is being fetched. Therefore this line).
This first render the default option, with the following code:
emptyPersonnelOption = (selected: boolean) => html
<option value="" ?selected="${selected}">- Select person -</option>
When loading the page where this selection is located everything is fine. All the relevant options are loaded in and I am able to select these options and save it. However, it goes wrong when I want to deselect an option and select the default one. It will show this option for a short time (about 1 second) and then becomes white.
Looking in the source code in the browser, it turns out that an extra empty option is added.
In the pictures above, I started with the second option selected (Tim Batist). I changed this to the default option (- select person -). You can see that this added a third option, which is almost empty (except for the value).
Question:
When I change to the default option in this selection, I want to see the default option. Now it will show just a blank field. I've tried some things, but I have no clue what the problem could be.
Upvotes: 0
Views: 1920
Reputation: 3130
It looks like you're setting a class variable this.personnel
instead of using the React state mechanism, which is necessary for triggering updates correctly. See React State and Lifecycle. Try something like this code:
${this.state.personnel.map(
({id, name}) =>
this.personnelSuggestionOption(id, name, selectedRelationId === Number(id)
))}
//...
this.setState({personnel: await fetch(getPersonnelByFunctionUrl(functionId))
.then(response => response.json())});
// If the list does not contain the current relation, add the current relation if it exists
if(this.shift.relation != null && !this.state.personnel.map(personnel => personnel.id).includes(this.shift.relation.id)) {
this.state.personnel = [...this.state.personnel, this.shift.relation];
}
You'll also want to initialize this.state.personnel
in the constructor, something like this:
constructor() {
this.state = {personnel: []};
}
Upvotes: 0