'Is there a way to access the event.target.value immedietly in onKeyPressed? (React Bootstrap Form Control)
<Form.Control
type="text"
onKeyPress={(event) => {
alert(event.target.value)
}
When I use the above code the value i can access is not updated as I want it to. When I type "a" the alert is "", and if I type another a giving "aa" the alert is showing "a". Is there a way to access also the latest typed value?
Solution 1:[1]
You can use onChange or onInput event instead of onKeyPress
Also, what you are trying to do is to show alert on input. I am not sure but most certain that event object is getting mutated somewhere in DOM manipulation. So, as soon as keyPress or any of the event for that matter happens it immediately fires alert() and at that time value of the event.target.value is not yet updated (event.target.value might still be referring the old value) so you see the value of empty string for 1st time or previous value next time.
once you close the alert the event execution goes on and it actually writes/updates the text you entered to the event.target.value.
so to summarize alert happens before it updates the target.value (due to some mutation happening on event object, value is not yet up to date at the time alert was fired) you see in the box
for that being said, I at least don't see a way of having the latest value in alert the way you are doing it.
if you want you can update some state value onKeypress and have an effect running on change of that value which will cause alert
example
const [input, setInput] = useState("");
useEffect(() => {alert(input)}, [input]);
<Form.Control onKeyPress={(e)=>setInput(e.target.value)} />
another naive way would be to wrap your alert into setTimeout (not recommended)
hope this helps !
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
