Actualmente estoy desarrollando un proyecto multiproveedor. Estoy tratando de agregar una funcionalidad en la que si un cliente quiere comprar un producto de una tienda de un proveedor diferente, no se agregará al carrito. Debe comprar al mismo vendedor.
Supongamos que hay dos proveedores x e y. El cliente quiere comprar en ambas tiendas de proveedores, pero la funcionalidad no intentará hacer esto, debe comprar en la tienda x o en la tienda y.
Mi funcionalidad para agregar al carrito está lista, pero no sé cómo puedo aplicar la condición if.
Estoy usando redux para la gestión del estado. Este es mi reductor de carro
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)); } En el código anterior, hay una variable isAlreadyVendor que devolverá -1 o 1. Entonces, básicamente, estoy tratando de hacer cuando isAlreadyVendor es -1, entonces el usuario puede agregar cualquier producto, pero después del segundo clic en el botón comprar ahora, la funcionalidad será verifique que isAlreadyVendor devuelva -1 o 1 si 1 significa que el usuario está tratando de comprar del mismo proveedor, entonces el segundo producto también se agregará al carrito, pero si isAlreadyVendor devuelve -1, entonces no se agregará nada (podemos mostrar una alerta)
// 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(); }