Home > Net >  Update object inside an array in useState React
Update object inside an array in useState React

Time:07-17

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( /* ?? */)
      }

CodePudding user response:

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]) //<---
      }

CodePudding user response:

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)
  }
  • Related