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

150
Visualizações
React TS universal hack for inputs with useState doesn't work as expected

I've seen typescript solution with universal handle change function, but in my case it works bad. Need help to understand why this happens.

When I add new product - it adds correctly, but when I try to clear Input manually - first rerender it also changes already added content.

Algorithm to see this mistake: fill inputs, add submit and remove one letter from title input - you'll see that it affects already added title in another state, but only on first rerender

Sandbox: https://codesandbox.io/s/restless-dream-do7bqh?file=/src/App.tsx

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

The below code-sample may be a solution to achieve the desired objective:

In the handleChange method:

setProduct(prev => ({ ...prev, [name]: value }));

Explanation

  • The prev value of product is taken as-is
  • Then, using the ... spread-operator all of prev's props are spread
  • This is now followed with [name] which is a new prop being added with value as the corresponding value
  • Any existing prop will be replaced.

Suppose name variable has the value 'title' and value is 'Testing 123', then the product object becomes:

product = {
  id: previousValueOfId,
  price: previousValueOfPrice,
  title: 'Testing 123'
}

Here, previousValueOfId and previousValueOfPrice are supposed to be the values.

Why OP's code did not get the desired result

The code is:

setProduct((prev) => {
  (prev as any)[name] = value;
  const newValue = { ...prev };
  return newValue;
});
  • This takes the prev product, and changes it's [name] prop.
  • When prev is changed, it may impact UI elements which are rendered using product.

(NOTE: I am still very new to ReactJS & if this is incorrect kindly update appropriately).

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