Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Count items based on condition

The initial state of the store is:

let initialState = {
  items: [],
  itemsCount: 0,
  completedCount: 0
};

When I dispatch an action with the type ADD_ITEM the new item is added to the items array and itemsCount is incremented (Although I'm not sure if I'm doing it correctly)

case "ADD_ITEM": {
  return {
    ...state,
    items: [
      ...state.items,
      {
        title: action.name,
        dateCreated: action.date,
        id: action.id,
        isChecked: false
      }
    ],
    itemsCount: state.items.length + 1
  };
}

and for TOGGLE_ITEM

case "TOGGLE_ITEM": {
  return Object.assign({}, state, {
    items: state.items.map(item => {
      if (item.id !== action.id) {
        return item;
      }
      return Object.assign({}, item, {
        isChecked: !item.isChecked
      });
    })
  });
}

When I dispatch an action with the type REMOVE_ITEM the following is executed:

case "REMOVE_ITEM": {
  return Object.assign({}, state, {
    items: [...state.items.filter(item => item.id !== action.id)],
    itemsCount: state.items.length - 1
  });
}

Now I'm trying to count the items that have isChecked is true

state.items.map(item => {
    if(item.isChecked){
        //Increment count
    }
})

I'm not sure where exactly to do that.

Inside the TOGGLE_ITEM action?

Inside a new COUNT_ITEM action? if so, when is that action dispatched?

And how do assign an incremented digit to part of the state?

like image 386
Zakher Masri Avatar asked Aug 01 '26 16:08

Zakher Masri


1 Answers

You can just compute it when you need it in your actions/components etc:

items.filter(item => item.isChecked).length

It's not a good practice to store derived values such as the count of certain items (including the itemsCount variable) in your state (reasons similar to why you normalise your state).

If you are worried about performance (it's O(n) so shouldn't be much of an issue in general), you can use a memoization library.

like image 138
Roy Wang Avatar answered Aug 04 '26 06:08

Roy Wang



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!