Reputation:
Whenever I type on input
field, I am getting the following error:-
Cannot read property 'value' of null
I have one form in which I have one input
field search value when I try to type anything I am getting the error.
Here is my code.
The issues on this function
handleInputFieldChange = (event, name) => {
this.setState(preState => ({
...preState,
form: {
...preState.form,
[name]: event.target.value
}
}));
};
Upvotes: 1
Views: 971
Reputation: 118261
There is a warning from React lib itself, which basically guides you how to solve this.
Warning: This synthetic event is reused for performance reasons. If you're seeing this, you're accessing the property
target
on a released/nullified synthetic event. This is set to null. If you must keep the original synthetic event around, useevent.persist()
So the fix is get a reference of the target object in a local variable like below.
handleInputFieldChange = (event, name) => {
const { target } = event;
this.setState(preState => ({
...preState,
form: {
...preState.form,
[name]: target.value
}
}));
};
This is only happened when you are using updater function with setState
method. They asked to use event.persist()
, but in my application, just take the reference of the target
object to use it inside the update function, which works 100%.
Checkout the doc of Event Pooling
The SyntheticEvent is pooled. This means that the SyntheticEvent object will be reused and all properties will be nullified after the event callback has been invoked. This is for performance reasons. As such, you cannot access the event in an asynchronous way.
If you want to access the event properties in an asynchronous way, you should call event.persist() on the event, which will remove the synthetic event from the pool and allow references to the event to be retained by user code.
Upvotes: 2