Not getting a return from React-redux

35 Views Asked by At

I want to filter the results from my store in React-Redux. Therefor I have created a filter selector.

My code only returns all the "shoppers", while it should only be returning the filtered shoppers.

Each shopper has an array of reviews that contains (one or more) objects with the review (text) and review number. We want to filter on the review number. See printscreen:

enter image description here

So to clarify, I want to filter by the reviews of a shopper and if that number >= the filter to then return only the shoppers that match this criteria.

What am I doing wrong here? How can I get it to return only the filtered results?

export const selectShoppersWithFilters = (filters) => (state) => {
  let shoppers = [...state.publicShoppers];

  if (filters.minAverageReview) {
    return shoppers.filter((shopper) => {
      return shopper.reviews.map((review) => {
        if (review.review >= filters.minAverageReview) {
          return (shoppers = shopper);
        }
      });
    });
  }
  console.log(shoppers);
  return shoppers;
};

ps. bear with me, I'm a junior developer...

1

There are 1 best solutions below

0
On BEST ANSWER

Assuming you are trying to filter shoppers that have "at least one review higher than minAverageReview" I think a filter function is enough, you don't need map.

      return shoppers.filter((shopper) => {
        return
            shopper.reviews.some((review) => review.review >= filters.minAverageReview) 
      });

So in the filter function, you pass a callback that checks for each element and decide to filter out that element or not based on your own criteria, the callback function must return a boolean. The element that doesn't satisfy the criteria (callback returns false) will be filtered out. Here my some() checks if the array (shopper.reviews) has at least one review element that has review higher than minAverageReview.