I have the following code:
const handleInputChange = (evt) => {
evt.preventDefault();
setTimeout(() => {console.log(evt)}, 500);
}
I have a search bar and every time I type something into the handleInputChange function gets called. When looking at the console I find that the evt.target.value field is always set to an empty string regardless of any inputs I have made.
However, if I modify the code to be
const handleInputChange = (evt) => {
evt.preventDefault();
const term = evt.target.value;
setTimeout(() => {console.log(term)}, 500);
}
My target value always gets printed correctly. Can anyone help clarify on why this happens?
When you pass the full event object you and you print the value you are getting the current object status because it is a reference to the original object, so if you clear de input or the event is destroyed your data is not available.
When you save the current event target value you do not care about event status so it is better to save your value instead propagate the event reference through functions.