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

101
Vistas
Updating object in array hook react js

I trying to update the quantity by pressing the "up" button.

This is my code.

const increaseHandler = (x) => {

    let newCart = [...props.cartItems];

    let exist = newCart.find((item) => item.id === x.id);
    if (exist) {
        exist.quantity++;
    } else {
        exist = {
            ...props.cartItems,
            quantity: 1,
        };
    }
    newCart.push(exist);
    props.setCartItems(newCart);
};

Here is the button:

<button className="up" onClick={() => increaseHandler(items)}>
    up
</button>

Every time I click on the "up" button, it appends a duplicate of the item on the cartItems

Image for initial cartItems

Image for the problem after increasing the quantity here

I increased the quantity but it appends the object to the array.

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

0

Even though you've shallow copied the cart items array you are still mutating the individual items with the post increment.

const increaseHandler = (x) => {
    let newCart = [...props.cartItems];

    let exist = newCart.find((item) => item.id === x.id);
    if (exist) {
        exist.quantity++; // <-- mutation!!
    } else {
        exist = {
            ...props.cartItems,
            quantity: 1,
        };
    }
    newCart.push(exist); // <-- adds duplicate items
    props.setCartItems(newCart);
};

You still need to create a new item reference, shallow copying the properties and updating the quantity property. You should only push new elements into the cart array.

const increaseHandler = (x) => {
    const newCart = [...props.cartItems];

    let exist = newCart.find((item) => item.id === x.id);
    if (exist) {
        exist = {
            ...exist,
            quantity: exist.quantity + 1;
        };
    } else {
        exist = {
            ...props.cartItems,
            quantity: 1,
        };
        newCart.push(exist);
    }
    
    props.setCartItems(newCart);
};

It's more common to map the previous state to the next state, and I suggest using a functional state update to ensure correctly updating from the previous state versus any state closed over in callback scope (possibly stale).

const increaseHandler = (x) => {
  props.setCartItems(items => {
    const inCart = items.some((item) => item.id === x.id);
    if (inCart) {
      return items.map((item) => item.id === x.id 
        ? {
          ...item,
          quantity: item.quantity + 1,
        } 
        : item);
    }
    return items.concat({
      ...props.cartItems,
      quantity: 1,
    });
  });
};
about 4 years ago · Juan Pablo Isaza Denunciar

0

You can update by using map:

const increaseHandler = (x) => {
  props.setCartItems((preState) =>
    preState.map((item) => (item.id === x.id ? { ...item, quantity: item.quantity + 1 } : item)),
  );
};
about 4 years ago · Juan Pablo Isaza Denunciar

0

You're setting the entire cartItems array into the single exist object you've created. So you're adding the entire cart to exist and then setting exist.quantity to be 1, and pushing that whole thing into newCart and setting it into state.

Try spreading exist rather than props.cartItems in your else block.

Based on your images and nomenclature, is this the FreeCodeCamp/Wiebenfalk tutorial on react & TS? If so, I did the same tutorial, and here's my add to cart function:

const handleAddToCart = (clickedItem: CartItemType) => {
setCartItems((prevState) => {
  // check if item is in cart by looking for id of clicked item in array of cartItems already in state
  const isItemInCart = prevState.find((item) => item.id === clickedItem.id);
  if (isItemInCart) {
    // search for item id matching clicked item; increment that amount
    return prevState.map((item) =>
      item.id === clickedItem.id
        ? { ...item, amount: item.amount + 1 }
        : item
    );
  }
  return [...prevState, { ...clickedItem, amount: 1 }];
});
};
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