1
votes

I have a shopping cart Component in REACT where selected products to be added in Cart & Store their IDs in local Storage. Now Before Checkout, Cart is shown which has all products details(name, unit price, qty, totalPrice) user has added. Initially Qty is 1 for all products that that in the cart and quantity input field is shown in front of the each product, where user can increase/decrease Qty. There is a Total Price column which should be updated whenever Qty changes**(unitPrice*Qty).**

I am using map() function to display all products in Cart. But when I update Qty for one product, it updates TotalPrice for all products instead of only that particular one. I know this is because onChange event I am storing Qty value in state and multiply it with UnitPrice so its doing it for all.

NOTE: I am not using Redux/Flux for this

I am not sure how to deal with this in map() function. Should I use index for this? Here is Cart component:

export default class Cart extends Component
{
  constructor(props) {
      super(props);

      this.state = {
        data:[],
        customer: '',
        redirectToReferrer: false,
        cart: [],
        cartItems: [],
        qty: ''

      };
      
      this.onChangeQty = this.onChangeQty.bind(this);

}

componentDidMount() {


    const retrieved = localStorage.getItem("cartItem");
    const arr = JSON.parse(retrieved);

    axios.post('http://localhost/Auth/api/customers/show_cart.php', arr,
   {headers: {'Accept': 'application/json, text/plain, */*',
              'Content-Type': 'application/json'}
 } )
    .then(response => {
      console.log("API response, Items in Cart are: ");
      console.log(response.data.records);
      this.setState({
             cartItems :response.data.records
           });      })
     .catch(error => {
     if (error) {
       console.log("Error Can't Show Cart Itemsfrom local Storage");}       });

}
onChangeQty(e)
{

this.setState({
  qty: e.target.value
})

}


  render()
  {

    return (
<div>
<MiniDrawer  />

<div id="profileDiv">


<Row style={ {width: "100%"}}>
<Col sm="12" md="12" lg="12" >
<Card> <CardBody> <Row>

<Col md="12" lg="12" sm="12" xs="12">
<h1> <b> Your Shopping Cart </b>  </h1>
<hr/>
<Table>
<thead>
    <tr className="text-center">

        <th> Item# </th>
        <th> Image </th>
        <th> ID</th>
        <th> Name</th>
        <th> Unit Price </th>
        <th> Quantity </th>
        <th> Total Price </th>

    </tr>

</thead>

<tbody>

{this.state.cartItems.map( (item, i) =>

  <tr>

    <td className="text-center">
      <h4 key={i}> {i}</h4>
    </td>

    <td className="text-center">
    <Image src={"data:image/png[jpg];base64," +  item.Image}
     id="cartImage" alt="abc" />
    </td>

    <td className="text-center">
      <h4 >{item.SparePartID}</h4>
    </td>

    <td className="text-center">
      <h4 >{item.Name}</h4>
    </td>

    <td className="text-center">
      <h4>{item.Price} </h4>
    </td>

    <td className="text-center">
    
      <h4 key={item.SparePartID}>
      <input className="text-center"
       type="number"
      min="1"
      onChange={this.onChangeQty}
      />
      </h4>
    </td>

    <td className="text-center">
      <h4 key={item.SparePartID}>
      {item.Price*this.state.qty}
      </h4>
    </td>

  </tr>
)}
  </tbody>
</Table> </Col> </Row>
</CardBody></Card> </Col></Row>

<br/><hr/><br/>

</div> </div>
  ); }
  
}

Please Help me how to update the price of particular item whenever input field of Qty changes. Thanks.

1

1 Answers

1
votes

If you want to change the price of a particular item then you should change the price value of that particular item. In this case, you are changing the global state of the price.

Just do this.

you have an array of objects in state i.e this.state.cartItems

now in mapping function where you are changing price value just change this.

<td className="text-center">

  <h4 key={item.SparePartID}>
  <input className="text-center"
   type="number"
  min="1"
  onChange={(e)=>this.onChangeQty(e,i)}
  />
  </h4>
</td>

now inside that onChangeQuantity function 

onChangeQty(e, index){
 const {cartItems} = this.state;
 cartItems[i].Price = e;
 this.setState({
  cartItems
 })
}

Now in this you will pass index of that particular item of array in which you really want to change the price. hence it will change the price of that particular object (item).