Adding a Button that Dispatches an Action To Redux to Remove an Item from the ShoppingCart

Jamund Ferguson
InstructorJamund Ferguson

Share this video with your friends

Send Tweet
Published 3 months ago
Updated a month ago

This lesson creates a new reducer method called removeFromCart which accepts a product id as a string. We then add on onClick handler to our remove button that dispatches the removeFromCart action into our redux store.

One thing to consider is that it's important we avoid dispatching any kind of stale state into our redux store. React event handlers such as the onclick handler do a good job of keeping up-to-date when the component gets updated. If we were dispatching from a useEffect hook we'd need to ensure that any of our dispatched data, like the product id, was explicitly defined in the dependency array.

Here's a bit more info about the stale state issue: https://reactjs.org/docs/hooks-faq.html#why-am-i-seeing-stale-props-or-state-inside-my-function

Jamund Ferguson: [0:00] Open up the file cartSlice.ts, and in the reducers object let's add a new method called removeFromCart. removeFromCart is going to take two arguments -- state and an action of type PayloadAction, where you also need to pass in the payload type, which is going to be a string for the id. All we have to do here is say delete state.items [action.payload] .

[0:21] Then, at the bottom of the file where we export addToCart, let's also export the action for removeFromCart.

[0:27] In Cart.tsx, let's import removeFromCart action and let's also import useAppDispatch. At the top of the component type const dispatch = useAppDispatch and then down in our removeFromCart button, let's add an onClick handler which calls dispatch(removeFromCart) and pass in the id.

[0:48] Now, in my app, if I go to Products, add a couple things to my cart, hit back to the cart. When I remove them from the cart, you can see them removing from the Shopping Cart page. You can also see that the quantity immediately updates in my shopping cart icon.