I know I'm not supposed to mutate the input and should clone the object to mutate it. I was following the convention used on a redux starter project which used:
ADD_ITEM: (state, action) => ({ ...state, items: [...state.items, action.payload.value], lastUpdated: action.payload.date })
for adding an item - I get the use of spread to append the item in the array.
for deleting I used:
DELETE_ITEM: (state, action) => ({ ...state, items: [...state.items.splice(0, action.payload), ...state.items.splice(1)], lastUpdated: Date.now() })
but this is mutating the input state object - is this forbidden even though I am returning a new object?
To delete an item using Redux and JavaScript, we return a new array without the removed item. to add a switch statement into the cartReducer function. In it, we check if the DELETE_CART action is invoked. If it is, then we return an object with the new state that has the removed item gone.
Using Redux also means learning how it works, which again could be a waste of time if you don't need it. As a rule of thumb - and one shared by one of Redux's creators, Dan Abramov - you don't need to use Redux unless you're unable to manage state within React or other front-end frameworks you're working with.
To remove an element from an array of objects in React: Use the filter() method to iterate over the array. On each iteration check if a certain condition is met. The filter method returns an array containing only the elements that satisfy the condition.
No. Never mutate your state.
Even though you're returning a new object, you're still polluting the old object, which you never want to do. This makes it problematic when doing comparisons between the old and the new state. For instance in shouldComponentUpdate
which react-redux uses under the hood. It also makes time travel impossible (i.e. undo and redo).
Instead, use immutable methods. Always use Array#slice
and never Array#splice
.
I assume from your code that action.payload
is the index of the item being removed. A better way would be as follows:
items: [ ...state.items.slice(0, action.payload), ...state.items.slice(action.payload + 1) ],
You can use the array filter method to remove a specific element from an array without mutating the original state.
return state.filter(element => element !== action.payload);
In the context of your code, it would look something like this:
DELETE_ITEM: (state, action) => ({ ...state, items: state.items.filter(item => item !== action.payload), lastUpdated: Date.now() })
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