Alex Advent
Alex Advent

Reputation: 187

useState delete array element in the state containing object

my state orderDetail contain orderDetail json

I am getting the _id of the order which I want to delete in function eg _id: 60f1ab20891ced4818b5ea87,

now I want to remove this order from the orders array which is in orderdetail and update the state.

orderdetail = {
  _id: 60f1ab20891ced4818b5ea86,
  totalPrice: '400',
  orders: [
    {
      _id: 60f1ab20891ced4818b5ea87,
      quantity: '1',
      price: 200,
      name: 'Caramel Latte',
      category: 'Steaming Cups'
    },
    {
      _id: 60f1ab20891ced4818b5ea88,
      quantity: '1',
      price: 200,
      name: 'Cinnamon Latte',
      category: 'Steaming Cups'
    }
  ],
  confirm: 'done',
  timestamp: 1626450720332,
  name: 'xxx',
  email: 'xxx',
}

what I did is clone state then uses for loop to find an index of the order then remove that index element in clone then update state to clone. any other less computation method?

Upvotes: 2

Views: 464

Answers (1)

Phil
Phil

Reputation: 164901

What you need to so is set a new object with the orders array filtered as well as a new totalPrice.

For example

const [orderDetail, setOrderDetail] = useState( /* whatever */ )

const deleteOrder = (id) => {
  setOrderDetail(prev => {
    // filter out the order by ID
    const orders = prev.orders.filter(({ _id }) => _id !== id)
   
    return {
      ...prev,
      orders, // overwrite orders
      totalPrice: orders.reduce((total, { quantity, price }) =>
          total + quantity * price, 0), // calculate new total
      timestamp: Date.now() // perhaps you want to update this too
    }
  })
}

This uses the functional update version of the useState() hook to easily get access to the previous state value.

Upvotes: 1

Related Questions