Aien Saidi Aien Saidi - 3 months ago 21
React JSX Question

Unexpected redux .filter result

So going straight to the question, I've a filter list in my redux store, and there are filters which will be added and removed from it.

adding filter as follows:

case ADD_FILTER:
return {
...state,
filters: [
...state.filters,
action.filter
]
};


is working as expected. but when removing a filter:

case REMOVE_FILTER:
return {
...state,
filters: state.filters.filter(
filter => filter.type !== action.filter.type && filter.name !== action.filter.name
)
};


will remove all of filters from my list!

here is a sample representation of filters:

{
{
type: 'sampleType1'
name: 'value1'
},
{
type: 'sampleType2'
name: 'value1'
},
{
type: 'sampleStatus1'
name: 'value2'
},
{
type: 'sampleStatus2'
name: 'value3'
},
}


and actions:

export function addFilter(filter) {
return (dispatch) => {
dispatch({
type: ADD_FILTER,
filter
});

dispatch(load());
};
}


,

export function removeFilter(filter) {
console.log(filter);
return (dispatch) => {
dispatch({
type: REMOVE_FILTER,
filter
});

dispatch(load());
};
}


I'm suspecting that there must be a problem with
.filter()
function.

I hope that I've explained everything.

Answer

If you only want to remove the filter specified, you should be using the or || operator:

filter => filter.type !== action.filter.type || filter.name !== action.filter.name