How can I delete an item inside a nested array with Hooks?

I am trying to remove a single item from state inside a nested array, but i am really struggling to understand how.

My data looks as follows, and I’m trying to remove one of the ‘variants’ objects on click.

const MYDATA = {
    id: '0001',
    title: 'A good title',
    items: [
      {
        itemid: 0,
        title: 'Cheddar',
        variants: [
          { id: '062518', grams: 200, price: 3.00},
          { id: '071928', grams: 400, price: 5.50},
        ]
      },
      {
        itemid: 1,
        title: 'Edam',
        variants: [
          { id: '183038', grams: 220, price: 2.50},
          { id: '194846', grams: 460, price: 4.99},
        ]
      },
      {
        itemid: 2,
        title: 'Red Leicester',
        variants: [
          { id: '293834', grams: 420, price: 4.25},
          { id: '293837', grams: 660, price: 5.99},
        ]
      }
    ]
  }

Against each variant is a button which calls a remove function, which (should) remove the deleted item and update the state. However, this is not happening and I’m not sure what I am doing wrong.

const [myCheeses, setMyCheeses] = useState(MYDATA);

const removeMyCheese = (variantID, itemindx) => {
    console.log(variantID);

    setMyCheeses((prev) => {
      const items = myCheeses.items[itemindx].variants.filter(
        (variant) => variant.id !== variantID
      );
      console.log(items, itemindx);
      return {
        ...myCheeses.items[itemindx].variants,
        items
      };
    });
};

An example of the issue I’m facing can be seen here https://codesandbox.io/s/funny-dan-c84cr?file=/src/App.js

Any help would be truly appreciated.

Answer

The issue is that, setMyCheeses function not returning the previous state including your change(removal)

Try one of these functions;

1st way

  const removeMyCheese = (variantID, itemindx) => {
    setMyCheeses((prev) => {
      const items = myCheeses.items[itemindx].variants.filter(
        (variant) => variant.id !== variantID
      );
      const newState = prev;
      newState.items[itemindx].variants = items;
      return {...newState};
    });
  };

https://codesandbox.io/s/bold-worker-b12x1?file=/src/App.js

2nd way

  const removeMyCheese = (variantID, itemindx) => {
    setMyCheeses((prev) => {
      const items = myCheeses.items.map((item, index) => {
        if (itemindx === index) {
          return {
            ...item,
            variants: item.variants.filter(
              (variant) => variant.id !== variantID
            )
          };
        } else {
          return item;
        }
      });
      return { ...prev, items: items };
    });
  };

https://codesandbox.io/s/sharp-forest-qhhwd