Answer the question
In order to leave comments, you need to log in
How to properly filter a list in Redux?
Tried to do filtering in Redux.
So far, I see the best solution to do filtering in the same way as it is done in regular React.js without Redux. Those. the parent function is passed to the child component, in which the state of the parent component is changed.
I came to the conclusion that reducers should not be used here, because the state of the store does not change. In addition, if you change it, you will not be able to display one list in several components with different filtering.
An example of my solution is written below. I wanted to know - is this approach to filtering correct in Redux or is there a better, more correct one?
Parent component (container):
handleFilterUpdate(filterType, filterValue ){
this.setState({ filterType: filterType, filterValue: filterValue });
}
render () {
const listItems = this.props.listItems;
return (
<div>
<MyFilter onFilterUpdate={this.handleFilterUpdate.bind(this)} />
<List items={getFilteredItems(listItems, this.state.filterType, this.state.filterValue)}/>
</div>
);
}
handleClick(e) {
this.props.onFilterUpdate('filter_type', this.refs.filterInput.value);
}
render() {
return (
<div>
<input type="text" ref = "filterInput"/>
<button onClick={this.handleClick.bind(this)}>Apply filter</button>
</div>
);
}
Answer the question
In order to leave comments, you need to log in
Store the filter type in store and not in state. Then filter from the shared array by that filter during mapStateToProps (changing the filter is an action). In this case, it would not be bad to use reselect.
function mapStateToProps(state) {
const filter = state.something.filter
const items = state.other.items
return {
items: filterItems(items, filter)
}
}
connect(mapStateToProps)(...)
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question