React Redux: Removing From an Array
Last week, I talked about how to add to an array in Redux. This week, to build upon and complement that, I’ll be talking about how to remove an item from an array. It’s not as easy as it may sound. It took me some Googling to find the answer to this question.
This is our initial state:
state={title: '',resultCt: 0,searchResults: {},nominations: []}
And we’re trying to change nominations
. Given the nomination index in the array, this is how we would remove an item in nominations:
case 'REMOVE_NOMINATION':return {...state,nominations: [...state.nominations.slice(0, action.nominationIndex),...state.nominations.slice(action.nominationIndex + 1)]}
We have to spread ...
the state, then slice it up to the nomination index, and concatenate it with the other half of nominations, sliced 1 more from the nomination index up until the end.
Usually, removing an item is pretty easy to do. For redux though, this was not the case. It was quite difficult to understand how to remove an item, but at least I now know how to do it.
That’s it. Stay safe everyone!