Search code examples
reactjsobjectevent-handlingsetstate

React setState object key with conditional event target


I have a problem on setting object keys in state. So below code is a form with title, body, city and country. With the value given by user, I set them to state. But since country and city should be assign in 'address' object, I created a handler that checks if the value is country/city or not.

But turned out even if the condition is not met, and ELSE is running, still it uses the object assign in if condition.

So either it is a title or city, state is set inside the address object

Would you check where am I doing wrong?

Below is my form and handlers

class Postit extends Component {
  state = {
    title: "",
    body: "",
    address: {
      country: "",
      city: ""
    }
  };

  handleChange = e => {
    if (e.target.id === "country" || "city") {
      let address = Object.assign({}, this.state.address); 
      address[e.target.id] = e.target.value; 
      this.setState({ address });
      console.log("NewState", this.state);
   
    } else {
      console.log("Target is not city or country");
     this.setState({
        [e.target.id]: e.target.value
      });
    }
  };

  handleSubmit = e => {
    e.preventDefault();
    console.log(this.state);
  };
  render() {
    return (
      <div className="container">
        <form className="white" onSubmit={this.handleSubmit}>
          <h5 className="grey-text text-darken-3">Send your post</h5>
          {/* Title */}
          <div className="input-field">
            <input type="text" id="title" onChange={this.handleChange} />
            <label htmlFor="title"> Title</label>
          </div>
          {/* Body */}
          <div className="input-field">
            <textarea
              id="body"
              className="materialize-textarea"
              onChange={this.handleChange}
            />
            <label htmlFor="body"> Content</label>
          </div>
          {/* City / Country Select */}

          <div className="input-field">
            <input type="text" id="country" onChange={this.handleChange} />
            <label htmlFor="country"> Write your Country</label>
          </div>

          <div className="input-field">
            <input type="text" id="city" onChange={this.handleChange} />
            <label htmlFor="city"> Write your City</label>
          </div>

          <div className="input-field">
            <button
              className="btn pink lighten-1 center-align"
              style={{ marginTop: "10px", borderRadius: "6px", width: "100%" }}
            >
              Post it
            </button>
          </div>
        </form>
      </div>
    );
  }
}

Exmp, when I fill the title, The newState looks like this:

{title: "", body: "", address: {country:"", city:"", title:"test"}}

Thank you!


Solution

  • You're not checking the condition properly. if (e.target.id === "country" || "city") is always going to be true even if e.target.id is not "country", due to the or part where "city" is a truthy value. It should be if (e.target.id === "country" || e.target.id === "city")

     handleChange = e => {
        if (e.target.id === "country" || e.target.id === "city") {
          let address = Object.assign({}, this.state.address); 
          address[e.target.id] = e.target.value; 
          this.setState({ address });
          console.log("NewState", this.state);
    
        } else {
          console.log("Target is not city or country");
         this.setState({
            [e.target.id]: e.target.value
          });
        }
      };
    

    Hope this helps !