user11011546
user11011546

Reputation:

Input not changing state REACTJS

The input doesn't change it's text. It comes pre-filled from the database. For example, if it comes with the text: example, if I press for example the s key, it console logs examples but in the DOM in is still example. Here is the handle code:

handleChange = event => {
    this.setState({ [event.target.name]: event.target.value });
    console.log(event.target.name);
    console.log(event.target.value);
  };

and the input field:

<input 
  type="text" 
  className="form-control" 
  name="note" 
  id=" note" 
  value={this.state.insurance.note} 
  onChange={this.handleChange}
/>

EDIT (fixed the render problem, but I don't get the data that I want when I submit the form) Here is the code for my form:

handleSubmit = event => {
    event.preventDefault();
    var state = this.state;
    axios
      .put(`${API_URL}/` + state.id + `/update`, {
        tip: state.tip,
        date_exp: state.date_exp,
        date_notif: state.date_notif,
        note: state.note
      })
      .then(response => {
        console.log(response.data);
        // window.location = "/view";
      })
      .catch(error => {
        console.log(error);
      });
  }

and my button is a simple submit button:

<button className="btn btn-success" type="submit">Save</button>

Upvotes: 0

Views: 54

Answers (2)

Jolly
Jolly

Reputation: 1768

imjared's answer is correct: your problem is in the handleChange function, where you wrongly update the state.
That function should be something like the following one:

handleChange = event => {
    const insurance = Object.assign({}, this.state.insurance);
    insurance[event.target.name] = event.target.value;

    this.setState({insurance});
  };

In the first line of the function, you create a deep copy of the current object insurance saved in the state. Then, you update the copied object, and finally update the state.

Upvotes: 2

imjared
imjared

Reputation: 20584

You're changing this.state.note based on the name property of your input so it makes sense that this.state.insurance.note wouldn't see any updates.

If you try console.logging this.state above your <input>, I bet you'll see what you're after.

Upvotes: 2

Related Questions