'componentDidMount affects other component

I have a price counter component. When I try to decrease a product qty to 0 it is deleted successfully but it affects the following product's qty and gives it 0, not its actual qty.

// Component
handleIncrement = () => {
  this.setState({ qty: this.state.qty + 1 });
};

handleDecrement = () => {
  this.setState({ qty: this.state.qty - 1 });
};

componentDidUpdate(prevProps, prevState) {
  const { cartId, getQty, updateQty } = this.props;
  const { qty } = this.state;

  if (prevState.qty !== qty) {
    if (getQty) getQty(qty); // Parent CB
    if (this.props.qty) updateQty({ cartId, qty });
  }
}

// Action
export const updateQty = (item) => (dispatch, getState) => {
  dispatch({ type: CART_UPDATE_QTY, payload: item });
};

// Reducer
case CART_UPDATE_QTY:
  const { cartId, qty } = action.payload;

  // In case of qty = 0 => delete item & return new cart
  if (qty <= 0) {
    const newCart = cart.filter((p) => p.cartId !== cartId);
    localStorage.setItem("cart", JSON.stringify(newCart));
    return newCart;
  }

  // Update Qty
  const item = cart.find((p) => p.cartId === cartId);
  item.qty = qty;
  const filteredCart = cart.filter((p) => p.cartId !== cartId);
  const updatedCart = [...filteredCart, item];
  localStorage.setItem("cart", JSON.stringify(updatedCart));
  return updatedCart;


Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source