0

I have my state like

this.state = {
      data: [],
      dataloaded: false,
      isopen: false,
      firstname: '',
      lastname:'',
      email:'',
      gender: '',
      avatar: '',
      number:'',
      dob:new Date()
    };

And I am having form to update state,
every text input has onchange such as this onChange={this.handleOnChange("firstname")}
And my hndleOnChange function is:

handleOnChange = field => event => {
    console.log(event.target.value,field)
    this.setState({field: event.target.value})
  }

this doesnt work This is not updating the state but if i do

handleOnChange = field => event => {
    console.log(event.target.value,field)
    this.setState({[field]: event.target.value})
  }

this works

Why does adding bracket infront of objectname it gets correct?

Emile Bergeron
  • 17,074
  • 5
  • 83
  • 129
  • 1
    Does this answer your question? [Is it possible to add dynamically named properties to JavaScript object?](https://stackoverflow.com/questions/1184123/is-it-possible-to-add-dynamically-named-properties-to-javascript-object) – Emile Bergeron Dec 19 '19 at 20:02

1 Answers1

7

Adding brackets means the value of that variable becomes the object key. Without brackets, the literal name becomes the object key. As an example:

const key = "name";

const object = {
    key: "My Key",
    name: "My Name"
};

obj.key // "My Key"
obj[key] // "My Name" -> equivalent to obj["name"] or object.name

Check out MDN's Working with Objects for more information.

In you case, this code:

handleOnChange = field => event => {
    console.log(event.target.value,field)
    this.setState({field: event.target.value})
}

is trying to set a state property named field, instead of the state property associated with the value of the field variable.

Gabor Szekely
  • 1,108
  • 5
  • 14