aditya kumar
aditya kumar

Reputation: 3023

How to filter out items from redux state in reactjs

I am getting data from my backend where I get list of product and assign it to cartList state in redux reducer. And here I am trying to filter out the item which contain both of the field item.teamWith === 0 && item.priceType === "TEAM" and assigning filtered value to waitingList. But the problem is i tried several times but i don't see any value assigned to it. this is how my code looks like.

Code

const initialState = {
  isFetching: false,
  cartList: [],
  waitingItem: [],
  page: null,
  fetched: false,
  fetchError: null
};
 case actionTypes.GET_CART_SUCCESS:
      return {
        ...state,
        cartList: action.payload._embedded.cartResourceList,
        page: action.payload.page,
        waitingItem: state.cartList.filter(item => item.teamWith === 0 && item.priceType === "TEAM"),
        fetched: true,
        isFetching: false,
      };

appimage

Here waitingItem is not even available in my state. I don't know Why. Any help would be great.

Upvotes: 0

Views: 265

Answers (2)

Aadil Mehraj
Aadil Mehraj

Reputation: 2614

It seems you are assigning the waitingItem based on cartList returned by API response and filtering it accordingly. So, instead of using existing state which is not yet updated to set waitingItem, you need to use the actual payload, like this:

case actionTypes.GET_CART_SUCCESS:
      const cartList= action.payload._embedded.cartResourceList;
      const waitingItem = cartList.filter(item => item.teamWith === 0 && item.priceType === "TEAM");

      return {
        ...state,
        cartList,
        page: action.payload.page,
        waitingItem:waitingItem,
        fetched: true,
        isFetching: false,
      };

Upvotes: 1

zmii
zmii

Reputation: 4277

From your code

state.cartList.filter(item => item.teamWith === 0 && item.priceType === "TEAM")

and image, where cartList properties are present, there are no properties you are filtering by - teamWith and priceType, so you need to alter you filter function or logic.

Probably, when waitingItem is empty array, undefined or something like this Redux doesn't add it to state...

Upvotes: 0

Related Questions