5

I have a user object where they are able to edit their info (phone number, email, etc)

I am unable to access the input's name inside the setState callback and keep getting TypeError: Cannot read property 'name' of null

However when I log the event.target.name it shows to be there.

When I change a simple state it works:

Assuming the state value is the same as the target name.

this.setState({ [event.target.name]: value });

I am following this post to update the user object.

Sorry if this is a duplicate, I could not find what I was looking for.

  handleUserChange(event) {
    console.log(event.target.name);
    const value = event.target.value
    this.setState(prevState => ({
      user: {...prevState.user, [event.target.name]: value }
    }))

  }

Edit: I am binding it properly in the class constructor like so:

contructor(props) {
    super(props);
    ...
    this.handleUserChange = this.handleUserChange.bind(this)
}
Simon
  • 6,413
  • 6
  • 34
  • 57

1 Answers1

14

React is recycling this event. So the async call to setState wont know the value of event.target.name since the event is already gone. You need to make a copy of the value the same as you did with event.target.value.

 handleUserChange(event) {
    console.log(event.target.name);
    const name = event.target.name;
    const value = event.target.value;
    this.setState(prevState => ({
      user: {...prevState.user, [name]: value }
    }))

  }

From the docs: link

Other solution:

handleUserChange(event) {
    event.persist();
    const value = event.target.value;
    this.setState(prevState => ({
      user: {...prevState.user, [event.target.name]: value }
    }))

  }

Persists the values of the event.

Jeroen Wienk
  • 1,970
  • 16
  • 17