Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

163
Views
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?

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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.

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!