How to make my cart work better when I add a new item from the same product user can increase the quantity of the product instead of adding it to the cart.
Here is the code I have for my reducer:
import {ADD_TO_CART, REMOVE_FROM_CART, CLEAR_CART} from '../constants';
const initialState = {
cartItems: [],
totalPrice: 0,
};
const cartItems = (state = initialState, action: any) => {
switch (action.type) {
case ADD_TO_CART:
return {
...state,
cartItems: [...state.cartItems, action.payload],
totalPrice: state.totalPrice + action.payload.price,
};
case REMOVE_FROM_CART:
return {
...state,
cartItems: state.cartItems.filter(
cartItem => cartItem !== action.payload,
),
totalPrice: state.totalPrice - action.payload.price,
};
case CLEAR_CART:
return {...initialState};
}
return state;
};
export default cartItems;
I tried to do like so but it failed
import {ADD_TO_CART, REMOVE_FROM_CART, CLEAR_CART} from '../constants';
const initialState = {
cartItems: [],
totalPrice: 0,
};
const cartItems = (state = initialState, action: any) => {
switch (action.type) {
case ADD_TO_CART:
const theItem = state.cartItems.find(
product => product.name === action.payload.name,
);
if (theItem) {
return {
...state,
cartItems: [...state.cartItems, action.payload],
totalPrice: state.totalPrice + action.payload.price,
qty: theItem.qty + 1,
};
}
return {
...state,
cartItems: [...state.cartItems, action.payload],
totalPrice: state.totalPrice + action.payload.price,
};
case REMOVE_FROM_CART:
return {
...state,
cartItems: state.cartItems.filter(
cartItem => cartItem !== action.payload,
),
totalPrice: state.totalPrice - action.payload.price,
};
case CLEAR_CART:
return {...initialState};
}
return state;
};
export default cartItems;
I think there is no need to share action because the Cart works 100% well , But I will share it,
import {ADD_TO_CART, REMOVE_FROM_CART, CLEAR_CART} from '../constants';
export const addToCart = (payload: any) => {
return {
type: ADD_TO_CART,
payload,
};
};
export const removeFromCart = (payload: any) => {
return {
type: REMOVE_FROM_CART,
payload,
};
};
export const clearCart = () => {
return {
type: CLEAR_CART,
};
};
and finally the screen with the payload
const product = {
id: 1,
name: 'LAptop',
price: 1000,
qty: 0,
// imgURL:
// 'https://www.google.com/images/branding/googlelogo/2x/googlelogo_color_160x56dp.png',
};
....
<Button
title="Add 1"
onPress={() => {
dispatch(addToCart(product));
console.log(cartData);
}}
/>
....