Kara
Kara

Reputation: 77

How to reset the state to null if the input is empty?

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

Answers (3)

Jefski14
Jefski14

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

Ashok
Ashok

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

Stefan
Stefan

Reputation: 1511

Because after your IF statement this line will be executed

this.setState({ [name]: { ...this.state[name], [country]: e.target.value } });

Upvotes: 1

Related Questions