I am currently developing a multi-vendor project. I am trying to add a functionality where if a customer wants to buy a product from a different vendor shop it will not add to the cart. He must shop from the same vendor.
Suppose there are two vendors x and y. The customer wants to buy from both vendor shops but the functionality will not try to do this he must need to buy from x shop or y shop.
My add to cart functionality Is ready but I am confused about how can I apply the if condition.
I am using redux for state management. This is my cart reducer
addToCart: (state: any, { payload }: { payload: any }) => {
const itemIndex = state.cart.findIndex(item => item._id === payload._id)
// here I am checking is the vendor already available into the cart or not
const isAlreadyVendor = payload?.vendor?.email ?? state.cart.findIndex(item => item.vendor.email === payload.vendor?.email)
// Need to make an if condition here but confused how it would be.
if (itemIndex >= 0) { // this will increase the quantity
state.cart[itemIndex].cartQuantity = 1
toast.info(`${payload.title} quantity increased`, {
position: 'bottom-left'
})
} else {
const newCart = { ...payload }
state.cart.push(newCart)
toast.success(`${payload.title} added to cart`, {
position: 'bottom-left'
})
}
localStorage.setItem("cartItems", JSON.stringify(state.cart));
}
On the above code, there is a variable isAlreadyVendor
it will return -1 or 1. So basically I am trying to do when isAlreadyVendor
is -1 then the user can add any product but after the second click on the buy now button the functionality will check isAlreadyVendor
is returning -1 or 1 if 1 that means the user is trying to buy from the same vendor then the second product will also add to the cart but if isAlreadyVendor
return -1 then nothing will add(we can show an alert)
CodePudding user response:
// Every item in the cart needs to have the same vendor
// Also okay if the cart is empty.
const isSameVendor = state.cart.every(c => c.vendor.email === payload.vendor.email;
if (!isSameVendor) {
alert();
// Or maybe
clearCart();
}