user13877162
user13877162

Reputation: 45

ReactJS: update record of an object of an array within an array

I am learning reactJS, I was doing a practice example where I have to update a product and it’s quantity. The final output is required in the following form:

productData = [
    name: '',
    code: '',
    Quantity:  [specificationName: "", quantity: ""]
]

I have added functionality for adding record in productData. But I am facing problem in updating Quantity array. Instead of updating data, a new record is added in Quantity array. I am not using index because I have read that it’s not a good approach when our data is non-static.

Below is my code:

handleSubmit = (event) => {
   let productData = {};
   let specificationQuantity = [];

   const productForm = new FormData(event.target);

   for (var [key, value] of productForm.entries()) {
            
     if (key !== "name" && key !== "code" ){
              
       let updateQuantity = {
           specificationName: key,
           quantity: value
       }

       specificationQuantity.push(updateQuantity)
     }
            
    productData = {
      name: colorForm.get('name'),
      code: colorForm.get('code'),
      Quantity: specificationQuantity
    }
  }
  this.state.productData.push(productData)
}

Let's say, I have the following 2 record after addition

  {
    code: "#0000C3",
    name: "Blue",
    Quantity: Array(2)
       0: {name: "", quantity: ""}     // this record is automatically created idk why
       1: {name: "v1", quantity: "1"}
  }
  {
    code: "#00001E",
    name: "Black",
    Quantity: Array(2)
       0: {name: "", quantity: ""}  
       1: {name: "v2", quantity: "2"}
  }

and when I try to update the quantity of “v1” to 3 then only that quantity which is in Blue should be updated like {name: ‘v1’, quantity: ‘3’} but I am getting the following result

{
    code: "#0000C3",
    name: "Blue",
    Quantity: Array(3)
       0: {name: "", quantity: ""}     // this record is automatically created idk why
       1: {name: "v1", quantity: "1"}
       2: {name: "v1", quantity: "3"}
  }
  {
    code: "#00001E",
    name: "Black",
    Quantity: Array(3)
       0: {name: "", quantity: ""}  
       1: {name: "v2", quantity: "2"}
       2: {name: "v1", quantity: "3"}
  }

Upvotes: 1

Views: 145

Answers (1)

Tushar
Tushar

Reputation: 675

The problem lies in this line

this.state.productData.push(productData)

You are actually mutating the state directly which is why you are facing unexpected behaviour.

Please have a look at this: https://reactjs.org/docs/state-and-lifecycle.html#using-state-correctly

Upvotes: 1

Related Questions