0

my component state looks like this:

  this.state = { 
        user: {firstname: '', lastName: '', phoneNumber: '' }
     }

on an input change event, I want to set state. But the below code does not seem to be working. What am I stupidly doing wrong?

 handlePhoneNumberChange(e){
     this.setState({["users"]['phoneNumber']: e.target.value});
  }
Whymess
  • 697
  • 3
  • 8
  • 20

2 Answers2

3

You should update the state like this instead:

handlePhoneNumberChange(e) {
   let user = this.state.user;
   user.phoneNumber = e.target.value;
   this.setState(user);
}

You may also want to look into ES6 spread properties, which cleans this process up significantly.

Edit: Changed "spread operator" to "spread properties", thanks Felix.

  • 1
    You might want pass a function to setState, because .setState is async. In this simple case there probably won't be a problem. But it's considered as a good pratice to pass function instead like this : https://facebook.github.io/react/docs/state-and-lifecycle.html#state-updates-may-be-asynchronous – Vincent Taing Jul 19 '17 at 00:18
  • 1
    [`...` is not an operator!](https://stackoverflow.com/questions/37151966/what-is-spreadelement-in-ecmascript-documentation-is-it-the-same-as-spread-oper/37152508#37152508). If you are referring to spread **properties**, then you should say that. – Felix Kling Jul 19 '17 at 00:32
  • @FelixKling Oh, my bad, thanks for the correction :) – Ryan Harvey Jul 19 '17 at 00:34
1

I'm not really sure what you're doing, but if you want to set the phone number of the current user:

this.setState({ user: { ...this.state.user, phoneNumber: e.target.value } })

assuming you have access to experimental ES features like spread.

Otherwise,

this.setState({ user: Object.assign({}, this.state.user, {phoneNumber: e.target.value}) })
Tyler Sebastian
  • 9,067
  • 6
  • 39
  • 62