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

171
Visualizações
Error writing to input e.target.value in array

There is an array of inputs in two forms: 1. Empty when created. 2. With the created values from the server after creation and saving. My code for adding a value for each of the inputs in the array doesn't work in the second case and I don't understand what could be wrong. In the first case, the values are written normally, and in the second, nothing happens.

<input
  defaultValue={sectionValue[i].text}
  value={sectionValue[i].text}
  onChange={(e: React.ChangeEvent<HTMLInputElement>): void => {
    sectionValue[i].text = e.target.value;
    setSectionValue([...sectionValue]);
  }}
/>
about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

There are two issues:

  1. Any time you're changing state based on existing state, you're best off using the callback form of your state setter, because it's really easy for the handler to close over a stale copy of the state (sectionValue in your case).

  2. You're breaking one of the rules of state: don't directly modify state. You're directly modifying the sectionValue[i] object. So it's the same object, but with a different text property. Later you're copying the array, but you need to copy the object as well. Sometimes it'll happen to render correctly when you do this, but other times — often — it won't.

To fix both, change:

sectionValue[i].text = e.target.value;
setSectionValue([...sectionValue]);

to

setSectionValue(oldSectionValue => {
    const newSectionValue = [...oldSectionValue];
    newSectionValue[i] = {
        ...oldSectionValue[i],
        text: e.target.value
    };
    return newSectionValue;
});

There's more than one way to do that, but the basic things are: 1. Use the callback, and 2. Copy both the object and the array.


Side note: Since sectionValue is an array, I'd suggest using the plural for it (sectionValues).

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