Reputation: 77
I have some inputs with a state set to null
and when the end-user types something and delete all, the input came back to an empty string.
How can I set the state to get back to null
?
I have a problem with the IF statement below who is not working when the user delete all his sentence. The state is ""
instead of null
Thanks for your help
onChange = (e, name, country) => {
if (e.target.value === "") {
this.setState({ [name]: { ...this.state[name], [country]: null } });
}
this.setState({ [name]: { ...this.state[name], [country]: e.target.value } });
}
Upvotes: 0
Views: 1196
Reputation: 376
as @Stefan already said your second setState statement gets executed after the first if.
To shorten your code and make it work correctly you could use something along those lines:
onChange = (e, name, country) => {
this.setState({ [name]: { ...this.state[name], [country]: e.target.value ? this.target.value : null } });
this.target.value is false if value is "", undefined or null and true in all the other cases.
Upvotes: 1
Reputation: 2932
Please make onChange method
onChange = (event, name, country) => {
const { value } = event.target
this.setState({
[name]: { ...this.state[name], [country]: value ? value : null }
});
}
When country value blank string set back it to null
Upvotes: 0
Reputation: 1511
Because after your IF statement this line will be executed
this.setState({ [name]: { ...this.state[name], [country]: e.target.value } });
Upvotes: 1