Anon
Anon

Reputation: 307

How to delete some item from redux state by some rule

I want to delete the item in the array of objects if someone id in the object is the same with id in a payload.

My code:

case "MINUS_PRODUCT_FROM_CART": {
      const arr = state.cart.forEach((item, i) => {
        if (item[i].id === payload.id) {
          arr.splice(i, 1);
        }
      });
      return {
        ...state,
        cart: arr,
      };
    }

My payload look :

[
{title: "Product 1", price: "128", id: "15"},
{title: "Product 2", price: "9", id: "26"},
{title: "Product 2", price: "9", id: "26"}
]

If payload id === 26 I want to delete ONLY ONE object with this id

Thanks!

Upvotes: 0

Views: 56

Answers (2)

Blue
Blue

Reputation: 22921

IMO, you can write this a lot neater, without declaring any extra variables:

return {
  ...state,
  cart: state.cart.filter(item => item.id !== action.payload.id),
};

After looking at your question again, I realized that you only want to remove the first one. We can still use filter here, and simply add a check:

let removed = false;

return {
  ...state,
  cart: state.cart.filter(item => {
    if (!removed && item.id !== action.payload.id) {
      removed = true;
      return true;
    }
    return false;
  }),
};

Upvotes: 1

RK_oo7
RK_oo7

Reputation: 527

const arr = state.cart.filter((item, i) => {
      return item.id !== action.payload.id;
     });
 return {
        ...state,
        cart: arr,
      };

Upvotes: 1

Related Questions