Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

74
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!