1

Im using react's useState setter to handle the input of the user. It works, except for there is this one bug. For some reason, it is not detecting the first character that I enter into the text input field. It has an onChange handler attached to it. I have also console log it inside the handler to log out whatever the input is. And I can see that the first character will always be empty, then, whatever subsequent characters will be registered by the console log. In other words, if I enter 4 characters, it will only register it as 3 characters, and it will always be the first character that is ignored. Please see my code below.

  const [input, setInput] = useState('');

  const handleInput = (value) => {
    setInput(value);
    console.log(input)
  };

<ReactCodeInput className={classes.reactCodeInput} onChange={handleInput} value={input} fields={4} type="number" />
Kimbo
  • 191
  • 1
  • 10
  • *"I have also console log it inside the handler to log out whatever the input is."* - Are you specifically logging `input`, or `value`? Please update the code shown to match the code you are asking about. – David Mar 07 '22 at 18:47
  • @David sorry about that. I was logging input from the state. I updated my post. Thanks – Kimbo Mar 07 '22 at 18:51
  • This looks like a controlled input, but the controlling value is `pinCode`, not `input`. `input` isn't being used at all. – windowsill Mar 07 '22 at 18:51
  • Unless something is very different in React Native, state updates are asynchronous. The value you want to log is `value`, not `input`. Otherwise it will always be one value behind. – David Mar 07 '22 at 18:54
  • @windowsill Oh, I changed the variable and forgot to update while I was debugging. But right now the value that is attached to it is now "input". Apologies – Kimbo Mar 07 '22 at 18:55

2 Answers2

1

As mentioned by Deivid, the setInput(value) is not synchronous. If you want to access the input value as soon as it is changed try it using useEffect.

const [input, setInput] = useState('');

useEffect (() => {
    console.log("New updated input value:", input)
},[input]};

const handleInput = (value) => {
   setInput(value);
   console.log(input) //Will log old value
};

<ReactCodeInput className={classes.reactCodeInput} onChange={handleInput} value={input} fields={4} type="number" />
tahaf10
  • 180
  • 2
  • 10
0

The setInput(value); is not synchronous so if you put a console log after that to print the value it will show the old value. More information here useState set method not reflecting change immediately

Also, the pinCode doesn't exist I think that value should be the input.

I did the same inn this sandbox https://codesandbox.io/s/peaceful-shaw-t8260h?file=/src/App.js:228-233 you can take a look.