Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

165
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda