Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

153
Visualizações
First input character in useState setter is not being set

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" />
about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

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.

about 4 years ago · Juan Pablo Isaza Relatório

0

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" />
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda