File size: 1,785 Bytes
f5071ca
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
export const initialState = {
    cart: [],
    user: null,
    profile: null,
    products: [],
    categories: ["Phones", "Laptops"]
}

export const getCartTotal = (cart) =>
    cart?.reduce((amount, item) => item.price + amount, 0)

const reducer = (state, action) => {

    switch (action.type) {
        case 'ADD_TO_CART':
            // Logic for adding item to cart
            return {
                ...state,
                cart: [...state.cart, action.payload]
            }

        case 'EMPTY_BASKET':
            return {
                ...state,
                cart: []
            }

        case 'REMOVE_FROM_CART':
            // Logic for removing item from cart
            let newCart = [...state.cart]

            const index = state.cart.findIndex(
                item => item.id === action.payload
            )

            if (index >= 0)
                newCart.splice(index, 1)
            else
                console.warn(`can't remove product as ID ${action.payload} is not available`)

            return {
                ...state,
                cart: newCart
            }

        /*
        return {
            ...state,
            cart: state.cart.filter(item => item.id !== action.payload)
        }
        */
        case 'ADD_TO_PRODUCTS':
            // Logic for adding item to cart
            return {
                ...state,
                products: [...state.products, action.payload]
            }

        case 'SET_USER':
            return {
                ...state,
                user: action.user
            }
        case 'SET_PROFILE':
            return {
                ...state,
                profile: action.userName
            }
        default:
            return state
    }
}

export default reducer