0

I am trying to get the value of the Textfield as user types, both when typing or deleting. Currently I have:

<TextField
  autoFocus
  id="Numbers"
  label="num"
  type="number"
  fullWidth
  onChange={handleChange}
/>;

My on handleChange is:

const handleChange = (event) => {
  const val = event.target.value;
  setNumbers(val);
  console.log(numbers);
};

However, my number is always the previous input rather than the one the user currently has typed, what is the issue here?

vuongvu
  • 811
  • 6
  • 15
ashes999
  • 1,234
  • 1
  • 12
  • 36

2 Answers2

0

setNumbers doesn't immediately update numbers, within the change handler you only have access to the value of numbers at the point the change handler was created.

setNumbers will trigger a new render of your component, in which numbers will have the new value.

If you want to something with the new value, just use val

Marco
  • 625
  • 6
  • 24
0

setNumbers is an asynchronous method, so the log command will be put in the call stack first and actually run before you set a new value. To check if your code work, try using useEffect:

useEffect(() => {
  console.log(numbers);
}, [numbers]);

Ref: https://blog.bitsrc.io/understanding-asynchronous-javascript-the-event-loop-74cd408419ff

vuongvu
  • 811
  • 6
  • 15