Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TypeError: Cannot read property 'name' of null

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)
}
like image 970
Simon Avatar asked Sep 22 '17 19:09

Simon


1 Answers

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.

like image 150
Jeroen Wienk Avatar answered Nov 12 '22 07:11

Jeroen Wienk