File tree Expand file tree Collapse file tree 1 file changed +19
-1
lines changed
specialtea/src/store/CartContext Expand file tree Collapse file tree 1 file changed +19
-1
lines changed Original file line number Diff line number Diff line change @@ -9,10 +9,28 @@ const defaultCartState = {
9
9
10
10
const cartReducer = ( state , action ) => {
11
11
if ( action . type === 'ADD' ) {
12
- const updatedItems = state . items . concat ( action . item ) ;
13
12
const updatedTotalAmount =
14
13
state . totalAmount + action . item . price * action . item . amount ;
15
14
15
+ const existingCartItemIdx = state . items . findIndex (
16
+ item => item . id === action . item . id
17
+ ) ;
18
+
19
+ const existingCartItem = state . items [ existingCartItemIdx ] ;
20
+
21
+ let updatedItems ;
22
+
23
+ if ( existingCartItem ) {
24
+ const updatedItem = {
25
+ ...existingCartItem ,
26
+ amount : existingCartItem . amount + action . item . amount
27
+ } ;
28
+ updatedItems = [ ...state . items ] ;
29
+ updatedItems [ existingCartItemIdx ] = updatedItem ;
30
+ } else {
31
+ updatedItems = state . items . concat ( action . item ) ;
32
+ }
33
+
16
34
return {
17
35
items : updatedItems ,
18
36
totalAmount : updatedTotalAmount ,
You can’t perform that action at this time.
0 commit comments