简体   繁体   中英

Update value in nested object in React useState

I have this useState:

const [data, setData] = useState([
  {
    id: 1,
    options: [{ id: 1, amount: 0 }, { id: 2, amount: 0 }]
  },
  {
    id: 2,
    options: [{ id: 1, amount: 0 }, { id: 2, amount: 0 }]
  }
]);

so I need a function to update the option X from item X.

Like this:

const increase = (itemId, optionId) => {
   //setData(...) 
}

I tried doing something like this:

const increase = (itemId, optionId) => {
    const copy = [...data];

    const dataItem = copy.find((item) => item.id === itemId);
    const option = dataItem.options.find((item) => item.id === optionId);

    option.amount = option.amount + 1;
    setData(copy);
}

But it increases by two...

try this

setData((prevArr) => {
  return prevArr.map((item) => {

  if (item.id !== itemId) return item;

  const updOptions = item.options.map((opt) => (
     opt.id === optionId ? {
        ...option,
        amount: option.amount+1,
      } : option
   )
   return {
    ...item,
    options: updOptions,
  }
  })
})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM