Home > database >  React-Trying to append new item on setState object but just adding last one
React-Trying to append new item on setState object but just adding last one

Time:01-31

I have a array with objects(products)[{},{}] and im trying to append this objects value's to another objects key-values like

products.map((e) => {
   setProductPrices({
      ...productPrices,
      [e.title]: e.unitPrice,
   });
});

but it is setting just second key.

my console:

first

second

{second: 15}

CodePudding user response:

Indeed, because the setProductPrices is asynchronous and so the productPrices is not updated immedietely. So you are reusing the starting productPrices on each iteration, and it only keeps the last one.

A quick fix (you should not use this) would be to use the version where you provide a function that has access to the previous state of the state

products.map((e) => {
   setProductPrices((prevPrices) => ({
      ...prevPrices,
      [e.title]: e.unitPrice,
   }));
})

But the more correct way, would be to generate a local version and do a single update at the end

const updatedPrices = {...productPrices};
products.forEach((e) => {
   updatedPrices[e.title]= e.unitPrice;
})
setProductPrices(updatedPrices);
  • Related