0

I'm practicing React, developing a Store, for adding the feature of the Shopping Cart I use this example.

But in my implementation, even though my version is almost the same, the "add to cart" button doesn't differentiate between each product, meaning:

  • 1st click affect all the buttons not only the clicked one and the other buttons change to "add more" legend
  • each posterior click only adds more products of the same kind the user 1st clicked, ignoring if clicked another one.

Seems the error its caused by a mutation in a Reducer Function:

export const CartReducer = (state, action) => {
switch (action.type) {
    case 'ADD_ITEM':
      if (!state.cartItems.find((item) => item.id === action.payload.id)) {
        //-------HERE
        state.cartItems.push({
          //mutation here?
          ...action.payload,
          quantity: 1,
        });
        //-------
  }

  return {
    ...state,
    ...sumItems(state.cartItems),
    cartItems: [...state.cartItems],
  };

What would be an alternative to this? How do I push items in the state without a mutation?

The complete te file its here

Here you can check the deploy and replicate the error, and here its the correct functionality demo

Ivan Rubio
  • 15
  • 8

2 Answers2

0

You are mutating the original state, which is bad practice in redux. What you can do is something like this to prevent it:

export const CartReducer = (state, action) => {
    switch (action.type) {
        case 'ADD_ITEM':
            if (!state.cartItems.find((item) => item.id === action.payload.id)) {
                // If you have Lint problems with this declaration, you can set a variable before the switch
                const cartItems = [...state.cartItems, action.payload];

                return {
                    ...state,
                    ...sumItems(cartItems),
                    cartItems,
                };
            }

            return state;
    }
}
luissmg
  • 545
  • 4
  • 9
  • Didn´t work i get , TypeError: cartItems.reduce is not a function, here is a pic of the error https://res.cloudinary.com/lab-file-upload3/image/upload/v1609782085/Screen_Shot_2021-01-04_at_11.40.42_AM_smi9av.png – Ivan Rubio Jan 04 '21 at 17:37
  • I already know the problem. Sorry, I didn't know the code behind `sumItems`. It is even more simple I think. Already made the changes to my reply – luissmg Jan 04 '21 at 18:21
  • Still ain't working, 2 new errors arise now, i got a NaN in the number of icons added to the cart and the buttons never change, everithing else ramains the same https://res.cloudinary.com/lab-file-upload3/image/upload/v1609868024/Screen_Shot_2021-01-05_at_11.31.50_AM_etpz2k.png – Ivan Rubio Jan 05 '21 at 17:36
  • I guess that's not related to the original problem of this post. I can help you if you like, but I need to check all the remaining code to understand what's going on – luissmg Jan 05 '21 at 18:17
  • Tx men, I would really appreciate that, I'm super stack with this, if you need to explain something or else please let me know – Ivan Rubio Jan 08 '21 at 18:06
0

state.cartItems.push is wrong here, you are mutating the state (antipattern).

first you check whether your item exists as you did at the begging. If the item exists simply return the state. If not you can return you may return your state as

return {
                    ...state,
                    ...sumItems(state.cartItems + 1),
                    cartItems: [...state.cartItems, action.payload],
                };

Before going into details and complex update operations, you should be familiar with the topics array destruct, object destruct, shallow copy, spread operations, copying arrays, slice, splice, filtering operations. Otherwise you may perform some direct mutation as above.If they are too complex, you can use other libraries which make this operations easier, for example immutable.js But remember, using extra library will cause a small performance loss.

https://redux.js.org/recipes/using-immutablejs-with-redux

benchpresser
  • 2,171
  • 2
  • 23
  • 41
  • Didnt work, i get a TypeError: cartItems.reduce is not a function:https://res.cloudinary.com/lab-file-upload3/image/upload/v1609782274/Screen_Shot_2021-01-04_at_11.44.22_AM_vfh5qm.png – Ivan Rubio Jan 04 '21 at 17:45