Reputation: 3580
I've got a set of inputs which I would like to tie to respective properties of the component state (since no other components in the app will depend on these inputs' values, I do not want to store them in Redux.)
I've written a function which takes the input event's value and the type of the input, and is supposed to update the relevant property in the component's state.
However, when I log state, I can see that multiple values are being updated by the same input.
Can anyone see where I'm making a mistake?
searchInput = (typeOfFilter, placeholder) => {
return (
<input
className=""
type="text"
placeholder={placeholder}
onChange={e => {
this.updateInputValue(e, typeOfFilter);
this.filterPlots(this.props);
}}
/>
);
};
updateInputValue = (evt, typeOfFilter) => {
switch (typeOfFilter) {
case 'nextStageFilterString':
this.setState({ nextStageFilterString: evt.target.value });
case 'blockNameFilterString':
this.setState({ blockNameFilterString: evt.target.value });
case 'growerNameFilterString':
this.setState({ growerNameFilterString: evt.target.value });
case 'varietyFilterString':
this.setState({ varietyFilterString: evt.target.value });
case 'regionFilterString':
this.setState({ regionFilterString: evt.target.value });
case 'ripenessFilterString':
this.setState({ ripenessFilterString: evt.target.value });
}
};
Upvotes: 1
Views: 1056
Reputation: 104359
Because you forgot to use break
after setState inside switch
case. Check MDN Doc for details about switch
.
Write it like this:
updateInputValue = (evt, typeOfFilter) => {
switch (typeOfFilter) {
case 'nextStageFilterString':
this.setState({ nextStageFilterString: evt.target.value });
break;
case 'blockNameFilterString':
this.setState({ blockNameFilterString: evt.target.value });
break;
case 'growerNameFilterString':
this.setState({ growerNameFilterString: evt.target.value });
break;
case 'varietyFilterString':
this.setState({ varietyFilterString: evt.target.value });
break;
case 'regionFilterString':
this.setState({ regionFilterString: evt.target.value });
break;
case 'ripenessFilterString':
this.setState({ ripenessFilterString: evt.target.value });
break;
}
};
But you don't need this big code to update specific state property, because you are already passing the property name to updateInputValue
function.
Simply write it like this:
updateInputValue = (evt, typeOfFilter) => {
this.setState({
[typeOfFilter]: evt.target.value
})
}
Upvotes: 2