0

I wonder why this.setState function is giving this error when I START TYPING. I am using the arrow function for the same. It gives me the error 'Cannot read property 'name' of null'. But it works when i use the simple direct way of changing the state.

Here is my code:

class UpstreamForm extends Component {

    state = {
        name: '',
        email: ''
    }

    onSubmitHandler() {
        this.props.changeData(this.state)
    }

    changeHander(event) {
        this.setState((state) => {
            return {
                [event.target.name] : event.target.value
            }
        })
    }

    render() {
        return (
            <div>
                <form onSubmit={this.onSubmitHandler.bind(this)}>
                    <input 
                    type="text"
                    placeholder="name"
                    name="name"
                    onChange={this.changeHander.bind(this)}
                     />
                     <input 
                    type="text"
                    placeholder="email"
                    name="email"
                    onChange={this.changeHander.bind(this)}
                     />
                     <button>Submit!</button>
                </form>
            </div>
        )
    }

}

The one below works, but why not the one I did above?? REALLY CURIOUS!

changeHandler = (event) => 
        this.setState({
            [event.target.name] : event.target.value
        })
Karan Kumar
  • 2,678
  • 5
  • 29
  • 65
  • Does this answer your question? [What is event pooling in react?](https://stackoverflow.com/questions/36114196/what-is-event-pooling-in-react) – Emile Bergeron May 14 '20 at 21:47

2 Answers2

0

It worked, thanks @Al Aoutar Hamza.

As per React docs, all properties will be nullified after the event callback has been invoked. As such, you cannot access the event in an asynchronous way.

Solution : You should call event.persist() on the event while using callback functions.

 changeHander(event) {
        event.persist();
        this.setState((state) => {
            return {
                [event.target.name] : event.target.value
            }
        })
    }
Karan Kumar
  • 2,678
  • 5
  • 29
  • 65
  • 1
    Just put the `name` and `value` in a local variable inside the `changeHander` (typo in _handler_ also) scope. You don't _need_ the event, so you don't need to use _persist_. – Emile Bergeron May 14 '20 at 21:49
  • @EmileBergeron's solution is the preferred way to fix this. – sloreti Sep 17 '20 at 23:33
-1

It should work. I think the previous one is erasing your existing state. You need to just keep the previous state while updating the new one.

changeHander(event) {
    this.setState((state) => {
        return {
            ...state,
            [event.target.name] : event.target.value
        }
    })
}
Sifat Haque
  • 5,357
  • 1
  • 16
  • 23