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

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

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