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

105
Visualizações
How to handle a complicated state in react

Background: I am kind of new to react and am learning it, I have made some sites in it but i Highly doubt my way of appraching the problem.

So while handaling a complex state . For example lets say we have a cart which has a product which is a object and then it contains a quantity key now how can we make changes in that quantity, which will be the best way to do it ??

Example

const [cart , setcart] = useState([

{_id: "1",
    name:"product1",
    quantity: 2
},
{_id: "2",
    name:"product2",
    quantity: 1
}
]);

lets say we need to update the quantity count of the product with the id 2 to 5. What we be the best approach, my way of doing it will be.

setcart((items)=>{
const changingItem = items.find((item)=>{return item.id === "2"});
changedItem.quantity = 5;

const newCart = items;
newCart.push(changingItem);

return newCart;
    
})

thank you

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

0

setCart(items => items.map(item => item.id === "2" ? {...item, quantity: 5} : item)}
about 4 years ago · Juan Pablo Isaza Relatório

0

Just to notify this case of editing an existing product in the list, if you want to add products, you need to check if the item does not exist then push the new product in the array and return a new reference of the array.

const [cart , setcart] = useState([

{_id: "1",
    name:"product1",
    quantity: 2
},
{_id: "2",
    name:"product2",
    quantity: 1
}
]);


setcart((items)=> {
  // first you need to find the index of the target product.
  const itemIndex = items.find((item)=>{return item._id === "2"});
  
  // check if the item exist.
  if (itemIndex !== -1 {
    // Then edit the same object inside the array.
    items[itemIndex].quantity = 5;
  }

  // Create new instance of items array.
  const newCart = [...items];

  return newCart;
    
})

about 4 years ago · Juan Pablo Isaza Relatório

0

setCart((items) => {
const changingItem = items.find((item)=>{return item.id === "2"});
return [...items, {...changingItem, quantity: 5}]
});
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