Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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?

>Solution :

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(order => order._id !== id)
   
    return {
      ...prev,
      orders, // overwrite orders
      totalPrice: String( // ¯\_(ツ)_/¯ you've got a string for some reason
        orders.reduce((total, { quantity, price }) =>
          total + quantity * price, 0) // calculate new total
      )
    }
  })
}

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading