Home > front end >  First input character in useState setter is not being set
First input character in useState setter is not being set

Time:03-08

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" />

CodePudding user response:

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.

CodePudding user response:

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" />
  • Related