Make a simple Shopping Cart App using React & Redux part 3

A simple guide to learn how to use React & Redux to build a basic shopping cart app

Aya Bellazreg
3 min readDec 22, 2018

In the last part we learned how to display items and add them to our Redux store. This time, let’s do the opposite; we’ll remove the added items from the DOM and the store in additon to adding(and subtracting) quantity via our Cart component.

In order to add or subtract the quantity, we firstly need to add onClick events the same way we did before with the addToCart function. So inside our Cart.js file, let’s add the following code(will be explained later):

Adding/subtracting quantity, and removing an item.

To explain this, we’ll just take one example(adding to quantity) since all the other examples are pretty much the same;

So once the target is clicked, we called the addQuantity function from the props. Here is where we need the mapDispatchToProps function; It basically dispatches the action to the reducer, and then we of course have to add that function as a parameter in the connect component.

NOTE: Don’t forget to add all the mentioned actions into your cartActions file and then import them to the Cart.

Now let’s add some changes inside our reducer to make this all work;

Adding the new actions to our reducer.

Here I used the if statement, but we generally use the switch statement.

Now we’re going to display our total. For that, I’ve created another component called Recipe. So we want to import our total from the store and display it then add or remove this shipping, right? we’ve already done that a few times now, so you should be able to do it by your own now!

Recipe.js file

Now let’s handle our shipping actions:

  • Add the shipping from the total:
if(action.type=== ADD_SHIPPING){return{...state,total: state.total + 6      }}
  • Remove the shipping from the total:
if(action.type=== SUB_SHIPPING){return{...state,total: state.total - 6      }}

And now, the total should be updated depending on shipping option!

However, we should consider that when the user visits another page and comes back, the checkbox will remain unchecked but the value of total didn’t change. That will cause a problem; it will keep adding the shipping cost even when the checkbox remained unchecked because of the default action of the browser. So to solve that, we could simply add the componentWillUnmount() function:

componentWillUnmount() {if(this.refs.shipping.checked)this.props.substractShipping()}

We did target that checkbox using the name of our ref. We’ve already added a ref attribute to it, remember?

Full code of the Recipe component here:

Don’t forget to add it to your Cart component.

That’s it! I hope I gave you a little insight about the React and Redux use and a better understanding about the concepts that comes in with Redux.

Github repository

--

--