Search code examples
reactjsreduxfilterinclude

mistakes in filter in React state


I have got an initial state in reducer. I get from api products and I should check by key, if product was not repeated, I put it to the state. If was repeated - do nothing. Mistake is that filter does not work and products repeat.

    const defaultState = {  
      productsInMyList: [],
    };
   
 //get prodouct
        const { productsInMyList } = action.payload;
    
//check, if it is in state or not          
              const sameProductsInMyList =    
    !!state.productsInMyList.includes(
                productsInMyList.key
              );
         
          const newProductsInMyList = sameProductsInMyList
            ? state.productsInMyList
            : [...state.productsInMyList, productsInMyList];
    
          return {
            ...state,
            productsInMyList: newProductsInMyList,
            
          };

Solution

  • I suspect, based on a comment of yours, that state.productsInMyList is an array of objects and that productsInMyList is also an object. Array.prototype.includes only works with primitives and shallow object equality (i.e. reference equality).

    If you are comparing objects in an array and want to know if an array contains some element matching a criteria then you will want to use Array.prototype.some, i.e. does there exist some element in this array meeting this condition.

    const sameProductsInMyList = state.productsInMyList.some(
      product => product.key === productsInMyList.key
    );