Search code examples
react-nativereduxreact-reduxe-commercecart

Incorrect Item is being removed from React Native Redux


I have the following redux-reducer for a cart in a react native app. The issue is, when I try to remove the first item of the cart, only the last item in the list gets removed. How do I fix this error?

cart actions:

export const removeFromCart = (payload) => {
  return {
    type: REMOVE_TO_CART,
    payload,
  }
}

const cartItems = (state = [], action) => {
  switch (action.type) {
    case ADD_TO_CART:
      //destructure the payload (which is the item) and take id
      const {_id} = action.payload;
      //check if there are duplicates
      const dupe = state.find(obj => obj._id === _id);
      //if duplicates, return state, else return state with the new payload
      return dupe ? state : [...state, action.payload];
    case REMOVE_TO_CART:
      return state.filter(cartItem => cartItem !== action.payload);
    case CLEAR_TO_CART:
      //return empty state which clears cart
      return (state = []);
  }
  //return the state
  return state;
};

cart component code:

<IconButton
  icon="delete"
  color={"red"}
  size={25}
  onPress={() => {
  toggleModal();
  props.removeFromCart(item);
  Toast.show({
       type: "info",
       position: "top",
       text2: `${item.name.substring(0, 15)}... has been removed from cart!`,
       topOffset: 60,
    }}/>

//loop through the states from the redux store to convert into props so they can be used in this screen
const mapStateToProps = state => {
  const {cartItems} = state; //state coming from store
  return {
    cartItems: cartItems,
  };
};

//for grabbing actions from cartActions and adding and removing products
const mapDispatchToProps = dispatch => {
  return {
    clearCart: () => dispatch(actions.clearCart()),
    removeFromCart: item => dispatch(actions.removeFromCart(item)), //deleting a single item
  };
};

Solution

  • Could you change

    return state.filter(cartItem => cartItem !== action.payload);
    

    to:

    return […state.filter(cartItem => cartItem.id !== action.payload.id)];