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

76
Vistas
React setState is incorrectly updating
const [cartItems, setcartItems] = useState([] as Product[]);

const addItemToCart = (product: Product) => {
  setcartItems((preCartItems) => {
    const updatedcart = [...preCartItems];
    if(!updatedcart.length)
      updatedcart.push(product)
    // updatedcart[0].price original value 1
    updatedcart[0].price = updatedcart[0].price + 1 ;
    console.log(updatedcart[0].price); // prints 2
    console.log(updatedcart); // printed object is saying price value 3
    return updatedcart;
  });
};

I am unable to understand how the value is incremented automatically by 1 and why is the value on the object giving a different output compared to the value accessed by the dot operator

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

The problem is that you're mutating your state within the setcartItems.

Doing const updatedcart = [...preCartItems]; is not copying the objects in preCartItems, it's just spreading the reference of the same objects in a new array.

Then you're mutating the object here updatedcart[0].price = updatedcart[0].price + 1 ;.

This will lead to two different versions of the state, hence the inconsistent result.

If you want to copy the objects you should do

const updatedcart = preCartItems.map(item => ({ ...item }));

This returns a new array of new objects and you can do any operation you want on them. This way of copying an array of objects is also shallow, it only works for 1 depth level, if you want to copy also nested objects you need a more robust function.

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