0

I have an array of products that looks like this enter image description here I am trying to filter out products with a specific category,

 const filteredTrendingProducts = products.filter(
      (item) => item.data.category === "Kids"
    );

 setTrendingProducts(filteredTrendingProducts);

this returns and empty object yet I can clearly see in the array there is a data key and in data there is category.Why is the object returning empty?

  • 1
    can you try setTrendingProducts(prev => prev.filter((item) => item.data.category === "Kids")) – Azzy Dec 02 '22 at 10:12
  • can you try a console.log of filteredTrendingProducts after the filter? Does this return null ? – Emilien Dec 02 '22 at 10:14
  • 1
    Please include some more relavent code so that the community members can better understand the problem, nor they can only give guess instead of answers – Azzy Dec 02 '22 at 10:15
  • [Working fine for me!](https://codesandbox.io/s/frosty-firefly-ld4ecr?file=/src/App.js) – NeERAJ TK Dec 02 '22 at 10:18
  • 1
    You'll need to provide more context/code for us to see what the real issue is, such as sharing where you're logging `products` and how it's being populated. It could be an issue where you're trying to access a state value that hasn't been set yet, or maybe an issue with closures, but we can't tell without seeing more code. – Nick Parsons Dec 02 '22 at 10:30
  • I realise the issue was not with the logic,it was how I was accessing the data.I was trying to render the trendingproduct in page.The problem was in the how I was retrieving the products after fetching them. – Gilbert Intabo Dec 02 '22 at 10:39

2 Answers2

1

Your logic is correct. Perhaps your program's lifecycle is wrong.

When you have the wrong lifecycle, components might not have the correct data and still load. Because of this, perhaps, the data comes empty.

Allan Bontempo
  • 117
  • 1
  • 5
0

This is not an anwer but try putting console logs to debug the filter function

const filteredTrendingProducts = products.filter(
      (item) => {
        console.log("item.data", item.data);
        console.log("item.data.category", item.data.category);
        console.log(item.data.category === "Kids", item.data.category == "Kids");
        return item.data.category === "Kids"
      }
    );
Srushti Shah
  • 810
  • 3
  • 17