When operating my online store, I encountered a problem with the shopping cart functionality. It seems that if I rapidly increase the quantity of items in the cart by clicking too quickly, duplicates are generated in both the shopping cart and order list. I suspect there may be a bug in my code, and I wonder if it has something to do with the asynchronous function.
Please note that in this scenario, an API call is made every time an item is added, which is a requirement that cannot be changed at the moment.
async addProduct({ commit, state, dispatch, getters }, item) {
try {
if (getters.gotThisItemAlready(item)) {
console.error("ITEM ALREADY HERE");
dispatch("changeItemQuantity", { item, quantity: 1 });
return;
}
let { order } = JSON.parse(JSON.stringify(state));
item.quantity = 1;
if (!order.items.length) {
order = await API.createOrder([item]);
} else {
order.items.push(item);
order = await API.updateExistingOrder(order);
}
order.items.forEach((item: any, index: number) => {
const article = articles.find(
(a: any) => a.articleID === item.articleID
);
if (article) {
Vue.set(order.items, index, Object.assign({}, article, item));
}
});
commit("updateOrder", order);
} catch ({ message }) {
console.error(message);
}
},
async changeItemQuantity({ commit, state }, { item, quantity = 1 }: any) {
try {
let { order} = JSON.parse(JSON.stringify(state));
order.items.forEach((i: any, index: number) => {
if (i.articleID === item.articleID) {
if (
i.quantity + quantity > -1 &&
i.quantity + quantity <= item.stock[0].stock
) {
i.quantity += quantity;
}
if (i.quantity === 0) {
order.items.splice(index, 1);
}
}
});
order = await API.updateExistingOrder(order);
order.items.forEach((item: any, index: number) => {
const article = articles.find(
(a: any) => a.articleID === item.articleID
);
if (article) {
Vue.set(order.items, index, Object.assign({}, article, item));
}
});
commit("updateOrder", order);
} catch ({ message }) {
console.error(message);
}
}