I am making a small shopping cart, which you can add products to it, every product is of this format:
{
id: 1,
img: "",
title: "",
desc: "",
category: "",
price: 12,
quantity: 0,
}
id, price, and quantity are integers. In my shopping cart, I have only 2 actions defined, which you can add or remove to the shopping cart.
if the item is already there you have to increase the quantity, calculate the total price and total items in the cart.
I am using react-redux for this.
My reducer looks like this:
case ADD_PRODUCT_TO_CART:
const productInCart = state.products.find(
(p) => p.id === action.product.id
);
if (!productInCart)
return {
...state,
products: [...state.products, action.product],
};
updateQuantity(productInCart);
return {
...state,
products: [...state.products],
};
ADD_PRODUCT_TO_CART has to add a new item to cart if its not there already and if its there it updates its quantity.
and this is how I want to make sure the quantity of an object is increased, (later also can be decreased)
const updateQuantity = (product) => {
console.log("product quantity", product.quantity);
return product.quantity === 0
? { ...product, quantity: 1 }
: { ...product, quantity: product.quantity 1 };
};
in my product component I have the add action after the add button is clicked:
onClick={() => props.addProduct(item)}
and also:
const mapStateToProps = (state) => {
return {
products: state.products,
};
};
const mapDispatchToProps = (dispatch) => {
return {
addProduct: (product) => dispatch(addProductToCart(product)),
};
};
export default connect(mapStateToProps, mapDispatchToProps)(Product);
I can add a new item to the cart, but when I press again to add the item, it doesn't increase the quantity and when I console log the current object the quantity is 0.
updateQuantity returns a product object that supposes to increase the quanttity but it doesnt do it currectly.
I am running out of idea how should I fix this any idea?
earlier I had another queation which I removed.
CodePudding user response:
Your updateQuantity
function is never reached because you are return
-ing before it. Run your function before you return
. You might also want to set your result to a var.
if (!productInCart){
const updatedProduct = updateQuantity(productInCart);
return {
...state,
products: [...state.products, updatedProduct],
};
}