I would really appreciate if anyone could help me with this.
Objective : If the item added by clicking "+" :
- It needs to check if the order already exists (if yes, then increment the quantity)
- If not then append that item to the orders list
fullmenu contains the list of all items in the following schema :
{ _id: 5eef61450bd95e1f5c8f372f ,
name: "Burger" ,
category: "American" ,
price: "100" ,
isVeg: false,
qty: 0
}
ISSUE : It adds a new object of item even if it already exists in the orders array instead of just incrementing it's quantity
The main code logic :
const [total, setTotal] = useState(0);
const [orders, setOrders] = useState([]);
const [fullMenu, setFullMenu] = useState();
const addMore = (e) => {
let sign = e.target.innerText;
let id = e.target.id;
const newOrders = [...orders];
let order = newOrders.find(each => each.id === id);
// if the order already exists for the item
if (order) {
let _sign = sign === "+" ? 1 : -1;
// increase or decrease the quantity
order.qty = (order.qty || 0) + 1 * _sign;
// remove item from order list if qty = 0
if(!order.qty){
setOrders(orders => orders.filter(each => each.id !== id));
// setTotal(total => total - parseInt(order.price));
return;
};
// save
setOrders(newOrders);
if (sign === "+") setTotal(total => total + parseInt(order.price));
if (sign === "-") setTotal(total => total - parseInt(order.price));
return;
};
// if item doesn't exist in the order list
const item = fullMenu.find(each => each._id === id);
if (sign === "+") {
order = {
...item, qty: 1
};
setOrders(orders => [...orders, order]);
setTotal(total => total + parseInt(order.price));
};
}
JSX :
<div className="col-sm-4"><span id={each._id} onClick={addMore} category={each.category}>-</span></div>
<div className="col-sm-4"><FormCheckLabel className="qty" >{each.qty}</FormCheckLabel></div>
<div className="col-sm-4"><span id={each._id} onClick={addMore} category={each.category}>+</span></div>