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

158
Visualizações
React onChange event fires empty string on first input

Problem - There is no string output the very first time I type in text. This is causing the last character of whatever I enter into the output to not appear. Why is this?

Some state - Focusing on name property

const [options, setOptions] = useState({
    name: '',
    signOff: ''
});

Input

<input
 type="text"
 placeholder="Enter first name"
 name="name"
 id="name"
 onChange={(e) => handleNameChange(e.target.value)}
/>

Function to fire after input change

const handleNameChange = (name: string) => {
    setOptions({
        ...options,
        name
    });
    console.log(options);
};

Example console output after typing "hello" - Why the empty string for name property?

{name: '', signOff: ''}       options.tsx:17 
{name: 'h', signOff: ''}      options.tsx:17 
{name: 'he', signOff: ''}     options.tsx:17 
{name: 'hel', signOff: ''}    options.tsx:17 
{name: 'hell', signOff: ''}   options.tsx:17 
about 4 years ago · Juan Pablo Isaza
3 Respostas
Responde à pergunta

0

Its expected behaviour, because setStates are asynchronous, so when you log the state variable immediately after its being set, it logs previous value, not the updated one
If you just want to log the state changes, move console.log() to useEffect hook

const handleNameChange = (name: string) => {
    setOptions({
        ...options,
        name
    });
    console.log(options);
};
useEffect(() => {
  console.log(options);
}, [options]); 
about 4 years ago · Juan Pablo Isaza Relatório

0

You can add options variable as the second parameter to useEffect. This means that in every state change of this variable this function will be fired.

useEffect(() => {
  console.log(options);
}, [options]); 
about 4 years ago · Juan Pablo Isaza Relatório

0

This is how I do it and I haven't encountered any such problem. You can also use the same function for every other input, not just name.

<input
 type="text"
 placeholder="Enter first name"
 name="name"
 id="name"
 onChange={handleChange}
/>

const handleChange = (e) => {
    setOptions({
        ...options,
        [e.target.name]: e.target.value
    });
};
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