fandro
fandro

Reputation: 4903

Redux shopping cart example

I'am trying to understand the example named "shopping cart" giving for redux : https://github.com/reactjs/redux/tree/master/examples/shopping-cart

In this example you can add elements to your list of items, I tried to implement the function of remove a list of items :

But in the reducers folder there is an addedIds() function, I added a case to remove the element of the list but I don't know how to implement that, here is the function : the reste of my code is working fine I just don't know how to delete the product id from the array of addedIds.

const initialState = {
  addedIds: [],
  quantityById: {}
};

function addedIds(state = initialState.addedIds, action) {
  switch (action.type) {
    case ADD_TO_CART:
        console.log("added ADD");
      if (state.indexOf(action.productId) !== -1) {
        return state
      }
      return [ ...state, action.productId ];
    case REMOVE_TO_CART:
        console.log("removed ADD");
        // here is my problem
    default:
      return state
  }
}

I assumed I need to do something like here : Is this the correct way to delete an item using redux?

but I don't know how

Can you help me please ?

Upvotes: 0

Views: 4461

Answers (2)

just-boris
just-boris

Reputation: 9776

You can delete some element from array just filtering it out:

// ... skipped other cases from the switch
case REMOVE_TO_CART:
    return state.filter(productId => action.productId !=== productId)

Approach with .filter() function looks very short and produces a new array instance as it required by redux.

Upvotes: 7

fandro
fandro

Reputation: 4903

For those who have a similar problem here is the solution :

const initialState = {
  addedIds: [],
  quantityById: {}
};

function addedIds(state = initialState.addedIds, action) {
  switch (action.type) {
    case ADD_TO_CART:
        console.log("added ADD");
      if (state.indexOf(action.productId) !== -1) {
        return state
      }
      return [ ...state, action.productId ];
    case REMOVE_TO_CART:
        console.log("removed ADD");

      return [ ...state.slice(0,state.indexOf(action.productId),
          ...state.slice(state.indexOf(action.productId)+1))
      ];
    default:
      return state
  }
}

thanks to Josh Deeden who found this vidéo : https://egghead.io/lessons/javascript-redux-avoiding-array-mutations-with-concat-slice-and-spread

Upvotes: 2

Related Questions