-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathstore.ts
92 lines (81 loc) · 2.21 KB
/
store.ts
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
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
import { createStore } from 'redux';
import { composeWithDevTools } from 'redux-devtools-extension';
import products from './products';
// DEFAULT STATE
export interface ProductDataInterface {
id: string;
name: string;
imageUrl: string;
price: number;
isTaxed: boolean;
isImported: boolean;
}
export interface CartDataInterface {
productId: string;
quantity: number;
}
export interface StateInterface {
products: { [index: string]: ProductDataInterface };
cart: { [index: string]: CartDataInterface };
}
export const defaultState: StateInterface = {
products,
cart: {},
};
interface ActionTypesInterface {
[index: string]: string;
}
export const actionTypes: ActionTypesInterface = {
ADD_TO_CART: 'ADD_TO_CART',
REMOVE_FROM_CART: 'REMOVE_FROM_CART',
};
export interface ActionInterface {
type: string;
payload?: any;
}
// REDUCERS
export const reducer = (
state: StateInterface = defaultState,
action: ActionInterface,
): StateInterface => {
switch (action.type) {
case actionTypes.ADD_TO_CART: {
const productId = action.payload;
const cart = Object.assign({}, state.cart);
if (state.cart.hasOwnProperty(productId)) {
// Increase quantity if the product is already in the cart
const newQuantity = state.cart[productId].quantity + 1;
cart[productId].quantity = newQuantity;
} else {
// Add the product to the cart
cart[productId] = { productId, quantity: 1 };
}
return Object.assign({}, state, { cart });
}
case actionTypes.REMOVE_FROM_CART: {
const productId = action.payload;
const cart = Object.assign({}, state.cart);
delete cart[productId];
return Object.assign({}, state, { cart });
}
default: {
return state;
}
}
};
// ACTIONS
export const addToCart = (productId: string): ActionInterface => {
return {
type: actionTypes.ADD_TO_CART,
payload: productId,
};
};
export const removeFromCart = (productId: string): ActionInterface => {
return {
type: actionTypes.REMOVE_FROM_CART,
payload: productId,
};
};
export const initStore = (initialState: StateInterface = defaultState) => {
return createStore(reducer, initialState, composeWithDevTools());
};