I'm Using React for the first time and I am trying to filter a JSON response so that I can display a list of products.
When I log the result of the filter to the console I seem to get the correct data. However when I try and map over it and render it ".Products" seems to be undefined.
import React, { useContext } from 'react';
import { MenuContext } from '../context/menuContext';
function Category() {
const [categoryItems] = useContext(MenuContext);
const category = categoryItems.filter(element => element.CategoryName == "Rice");
console.log(category);
return (
<div>
<h1>Category Page</h1>
{category.Products.map(productItem => (
<h3 key={productItem.Id}>{productItem.ProductName}</h3>
))}
</div>
);
}
export default Category;
Update: Thanks @Ori Drori for your comment. I have tried to use .find and still does not work.
I think this is something to do with how react works. Becuase in the console I am getting an empty output before I get the correct result.
Update 2: I implemented the answer that I have marked as correct and its now working. HOWEVER. There are two things I don't understand and I would like someone to explain.
- When I call
console.log(console.log(category);
Why is it that in the console I see 'undefined' before I get the result with the data.
- Why do I need to put 'category &&' when I remove it. It stops working.


Array.filter()returns an array of items, so the theProductsare actually under.category[0].Products. UseArray.find()instead of a filter, because it returns only a single item.