I have following code:
const initialState = {
searchItems: ['Item'],
}
export default (state = initialState, action) => {
switch (action.type) {
case BACKSPACE_REMOVE_SEARCH_ITEM:
console.log(state.searchItems);
return {
...state,
searchItems: [...state.searchItems.splice(-1)],
};
default:
return state;
}
}
but when I try to execute such an action I receive same array as before with 'Item' inside, it doesn't' remove it. Where is a problem?
There is no “right” answer for this. Some users prefer to keep every single piece of data in Redux, to maintain a fully serializable and controlled version of their application at all times. Others prefer to keep non-critical or UI state, such as “is this dropdown currently open”, inside a component's internal state.
.splice
returns the deleted elements. Actually, you shouldn't use .splice
at all since it mutates the original array. I know you are spreading the original one but spread syntax makes shallow copies. So, be careful. .slice
would be better it also returns the deleted ones. In this case, you need to use a combination of .slice
and .concat
probably or you can use .filter
.
return {
...state,
searchItems: state.searchItems.filter( (_,i) =>
i !== state.searchItems.length-1
),
};
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