Reputation: 48490
I am attempting to implement a basic filter in my React app. I have two props that are managed by Redux. They look something like the following:
const mapStateToProps = state => {
return {
groceries: getSortedGrocers(state.groceries),
searchFilter: state.searchFilter
};
};
The problem I'm facing is when searchFilter
is updated, I need to filter the groceries
array, which is ultimately this.props.groceries
in my Component instance.
What is the best design pattern for this? Should I be using a lifecycle event so whenever searchFilter
is updated, I filter groceries
? Can I get pointed to the correct documentation for how to handle filtering properly so if a searchFilter
exists, I narrow down what groceries
to display? Ultimately, somewhere, something such as this will exist:
if ( this.props.searchFilter ) { groceries.filter( ... ) }
I'm just not entirely sure where to handle the filtering logic.
Upvotes: 0
Views: 59
Reputation: 870
Your filtering should be already done in Redux, in the getSortedGrocers function.
const mapStateToProps = state => {
return {
groceries: getSortedGrocers(state.groceries, state.searchFilter)
};
};
And in the Redux getter:
export const getSortedGrocers = (groceries, filter) => {
// do sorting here
};
That's the standard design pattern for filtering stuff, as far as I'm aware. You can also do the filtering on your render method, but that's not encouraged (though not any less efficient, funnily enough).
Upvotes: 2
Reputation: 2145
Whenever searchFilter is updated mapStateTopProps will be called. You can do the filtering in there. If you need to use existing props from the component you get them as a second param.
mapStateToProps = (state, existingProps) => {}
Maybe I'm misunderstanding the question. If some of the info you need is passed to the component as props you should use the second param.
Upvotes: 1