Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

131
Vistas
Update object inside an array in useState React

I have an object in useState that has an array inside called detail. This array contains objects that I need to update for example to change quantities or purchase prices.

createdAt: "2022/07/15"
detail: Array(2)
0:
name: "LINK AZUL"
provider: {uid: '6271a32082193f4b88e292f0', name: 'Genérico'}
purchasePrice: 195
quantity: 3
subtotal: 585
total: 0
_id: "62ab8f3cd0519268de938c8f"
[[Prototype]]: Object
1: {provider: {…}, _id: '62ab8ed6d0519268de938bc9', name: 'LINK ROJO', quantity: 3, purchasePrice: 186, …}
length: 2
[[Prototype]]: Array(0)
disabledBy: []
discount: 10
idProvider: {_id: '6271a32082193f4b88e292f0', name: 'Genérico'}

How can I access the _id of the object inside the detail array to be able to modify it and set it in useState?

I have tried with this code where I search for _id but then I don't know how to set it in the array of objects called detail so that only that object is modified without altering the rest Besides that I think it will not work properly.

const onChangePriceHandler = (id, e) => {
        let newPrice = Number(e.target.value)
       
        const updatePrice = products.detail?.map(data => {
          if (data.id === id) {
            return {
              ...data, purchasePrice: newPrice, subtotal: newPrice * data.quantity
            }
        } 
            return data
        })
        setProducts( /* ?? */)
      }
about 4 years ago · Santiago Gelvez
2 Respuestas
Responde la pregunta

0

What you could do is save the state to a variable and then update that variable's id to what you want and then after that set the state to that updated variable

  const functionThatUpdatesTheState = ()=> {
    let variable = stateValueWeHaveNow;
    variable......id = theUpdatedId; 
    setState(variable)
  }
about 4 years ago · Santiago Gelvez Denunciar

0

you can update the state by doing this

const onChangePriceHandler = (id, e) => {
        let newPrice = Number(e.target.value)
       
        const newProducts= products?.map(product=> {
            const dataIndex = (product.detail || []).findIndex((_data) => _data._id === id);
            const detail =
              dataIndex > 0
                ? [...product.detail].splice(dataIndex, 1, {
                    ...product.detail[dataIndex],
                    purchasePrice: newPrice,
                    subtotal: newPrice * product.detail[dataIndex].quantity,
                  })
                : product.detail;
          return dataIndex > 0
            ? {
                ...product,
                detail,
              }
            : product;
        })
        setProducts( [...newProducts]) //<---
      }
about 4 years ago · Santiago Gelvez Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda