From Redux
documentation, I know, that we never should mutate state and that's why we should use concat
and slice
methods, so I ended up with following reducer(most of actions removed for simplification):
export default function blocks(state = [], action) {
switch (action.type) {
case DELETE_BLOCK:
var index = state.findIndex(e => e.id === action.blockId);
return [...state.slice(0, index), ...state.slice(index + 1)];
default:
return state;
}
In my case I don't have index of element I want to delete, so can I use filter
? Like this:
export default function blocks(state = [], action) {
switch (action.type) {
case DELETE_BLOCK:
return state.filter(e => e.id !== action.blockId);
default:
return state;
}
filter
does not mutate the state, it returns a new Array
so there is nothing wrong here.
We try to avoid filter
when we are dealing with immutable
data since it always returns a new reference, breaking the reference equality check ===
. But if you don't use this kind of reference by trying to return the previous state reference if you think the state didn't change (and I think you're not doing this, it's ok), you don't need to worry about using filter
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With