Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

149
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda