Hello I am trying react for the first time and I am having some trouble with my filter function. Here's the code:
So this is my render method in my component:
const categoryFilter = this.state.appItems.filter(item =>
item.categories.filter(str => {
return str.includes(active);
})
);
const appList = categoryFilter.map(appItem => (
<AppItem appItem={appItem} key={appItem.id}></AppItem>
));
return (
<React.Fragment>
<div className="flex-container">
<NavCategories
categories={this.state.categories}
onClick={this.handleClick}
active={active}
/>
<section className="apps-list">
<header>
<input type="text" placeholder="Search by App" />
</header>
<ul>{appList}</ul>
</section>
</div>
</React.Fragment>
);
this.state.appItems is an array coming from a json file, here's a snippet:
[ {
"id": "12312",
"name": "Test",
"description": "test.",
"categories": ["Voice", "Delivery", "Optimization"],
"subscriptions": [
{
"name": "Trial",
"price": 0
},
{
"name": "Professional",
"price": 3500
}
]
},]
Active is a string to manage active class items on another component.
Everything renders correctly, but it is never filtered even though the active state is changing everytime. I have tried multiple ways, but this Filter method is getting me confused a lot because I want to filter an array thats inside another array and want to filter the whole AppItem array.
If anyone could explain/give me some tips I would love it. Thanks in advance :)
.lengthto the inner filter call to return an integer that will be falsey if empty and will properly trigger the outer filter.