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

100
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório

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 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