Reputation: 800
as the question says, how do I filter out and keep two categories in the same list, but the "third" category is in a separate section in React/redux?
My component:
{
categoryGrouping.map((category, i) =>
this.props[category].length > 0
? <Accordion title={`${trans(`HEADER_CATEGORY`)} - ${trans(`CATEGORY_${category}`)}`}
description={trans(`HEADER_TEXT_${category}`)}
expanded={category === Category.TSHIRTS}
key={i}
>
<SelectionList>
{
this.props[category].map((item, j) => <li key={j}><ListItem item={item}/></li>)
}
</SelectionList>
</Accordion>
: null
)
}
In my container:
const predicateFunc = category => item => item.category === category;
const sorter = (a, b) => new Date(b.createdAt).getTime() - new Date(a.createdAt).getTime();
const mapStateToProps = (state) => {
const list = (state.list.list || []);
return {
loaded: !!state.list.list,
[Category.UNDERWEAR]: list.filter(predicateFunc(Category.UNDERWEAR)).sort(sorter),
[Category.TSHIRTS]: list.filter(predicateFunc(Category.TSHIRTS)).sort(sorter),
[Category.JEANS]: list.filter(predicateFunc(Category.JEANS)).sort(sorter),
[Category.SWEATPANTS]: list.filter(predicateFunc(Category.SWEATPANTS)).sort(sorter),
error: state.list.error
};
};
Lets say I want 'JEANS' and 'SWEATPANTS' in the same list (but they are still two categories), but separate 'T-SHIRTS' and 'UNDERWEAR'.
How I want it:
Thanks in advance
Upvotes: 0
Views: 269
Reputation: 479
Group categories by schema:
const sorter = (a, b) => new Date(b.createdAt).getTime() - new Date(a.createdAt).getTime();
const groupCategories = ({ schema, list }) =>
Object.keys(schema).reduce(
(acc, category) =>
Object.assign(acc, {
[category]: list
.filter(item => schema[category].indexOf(item.category) > -1)
.sort(sorter),
}),
{},
);
const mapStateToProps = (state) => {
const list = state.list.list || [];
return {
loaded: !!state.list.list,
...groupCategories({
schema: {
Category1: [Category.TSHIRTS],
Category2: [Category.UNDERWEAR],
Category3: [Category.JEANS, Category.SWEATPANTS],
},
list,
}),
error: state.list.error,
};
};
Upvotes: 1
Reputation: 5926
I'd create a reducer / state for the categories:
// categories = [['T-SHIRTS'], ['UNDERWEAR'], ['JEANS', 'SWEATPANTS']]
const mapStateToProps = ({categories, list}) => (
categories.map(subCategories =>
list.filter(item => subCategories.indexOf(item.category) > -1))
)
Each category has an array of sub-categories and each item has a category field.
Upvotes: 1