Reputation: 253
I'm trying to add same item into cart and trying to make it only increase the quantity but whenever I added item to cart it will show 2 same items.
Here is my reducer:
import {
ADD_PRODUCT_BASKET,
GET_NUMBERS_BASKET,
LOADING,
SUCCESS
} from '../actions/type';
const initialState = {
products: [],
loading: false,
basketNumbers: 0,
cartCost: 0,
numbers: 0,
inCart: false
};
export default (state = initialState, action) => {
switch (action.type) {
case LOADING:
return {
...state,
products: [],
loading: true,
err: ''
};
case SUCCESS:
return {
...state,
products: action.payload,
loading: false,
err: ''
};
case ADD_PRODUCT_BASKET:
let numbers = (state.numbers += 1);
let inCart = (state.inCart = true);
let product = state.products;
return {
...state,
basketNumbers: state.basketNumbers + 1,
cartCost: state.cartCost + action.payload.price,
product: product.push(action.payload),
numbers: numbers,
inCart: inCart
};
case GET_NUMBERS_BASKET:
return {
...state
};
default:
return state;
}
};
and here is my cart:
function Cart({ basketProps }) {
const nf = new Intl.NumberFormat();
let productsInCart = [];
if (basketProps.inCart) {
productsInCart = basketProps.products;
} else {
productsInCart = [];
}
let productQuantity = 1;
{productsInCart.map((product, i) => (
<ProductInfo key={i}>
<Infor>
<Image src={product.img_url1} />
</Infor>
<Infor>
<ProductTitle>{product.title}</ProductTitle>
<ProductPrice>
<ProductQuantity>{productQuantity} x </ProductQuantity>
{nf.format(product.price)} vnd
</ProductPrice>
</Infor>
</ProductInfo>
))}
}
How can I make the quality increase instead of like add a new item into my cart?
Here is my github project if you want to look over my code:
https://github.com/nathannewyen/the-beuter
Upvotes: 0
Views: 497
Reputation: 10463
You need to hold a counter of each product. Now you just keep push
ing products into the array.
Instead of
product: product.push(action.payload),
You should do sth like
let products = [...state.product];
let foundProduct = products.find(prod => prod.title === action.payload.title);
if (foundProduct) {
foundProduct.quantity++;
} else {
action.payload.quantity = 1;
products.push(action.payload);
}
and then
return {
...state,
basketNumbers: state.basketNumbers + 1,
cartCost: state.cartCost + action.payload.price,
product: products,
numbers: numbers,
inCart: inCart
};
I don't know what are these other properties basketNumbers
and numbers
but I guess they are all related to product
array, so they can be removed.
Upvotes: 2