There is an input element in my code:
<input id="input" className="ml-2" type="number" name="Qty" min="1" max="999" value={qty} onChange={(e) => {changeQty(e)}}/>
And the onChange handler is:
const changeQty = (e) => {
setQty(e.target.value);
console.log(qty);
}
So I suppose that whatever I enter in the input field will be printed out in the console, but the fact is there is delay.
For example, the default value is 1, then I type 2, then 1 will be printed out. Then I type 3, then 2 will be printed out. The number printed out is the previous one I entered instead of the current one, as shown below:
Could anyone tell me how to remove the delay?
I read useState set method not reflecting change immediately, but still cannot solve it.
I tried the code below as the answer indicates,
useEffect(() => {
setQty(document.getElementById("input").value)
}, [qty]);
but an error ReferenceError: Cannot access 'qty' before initialization
occurred.
Thanks!