Create a Shopping Cart with the useState React Hook to Manage Product Quantity and Total

InstructorColby Fayock

Share this video with your friends

Send Tweet

If we're fortunate enough, not only will people want to buy one item from our store, they'll want to buy multiple. To do that, we need to provide a shopping cart, which allows us to store what items the customer wants to buy, how many of them, and how much these items will cost.

To do this, we can take advantage of React's built-in state management hooks to make sure we're accurately keeping track of their order.

We will save our cart data in useState that will be used to calculate the subtotal, total items, and total price that our customer has in their cart. During this process, we will move the Stripe Checkout flow out of our Product Cards and into a new checkout section. The product cards will add items to the state that we create.

Jose Paitamala
~ 2 years ago

My quantity doesn't increment one by one, it's weird but first time clicking the add to cart button it shows 1 quantity, but if clicking again it shows 3 quantity (instead of 2), and if clicking again it shows 5 quantity (instead of 3). Any idea?

BTT
~ 2 years ago

This is why https://reactjs.org/docs/strict-mode.html

Jose Paitamala
~ 2 years ago

Hi, I tried using this <React.StrictMode> but no warning shows, can you specify please? I have checked and the issue is also present if downloading the lesson github code.

BTT
~ 2 years ago

Try this build your next.js app and run yarn start and see if u are getting the problem

~ 2 years ago

You have to go to next.config.json and then you set reactStrictMode to false

~ 2 years ago

An issue with printing out the subtotal when clicking on "Buy Now"

console log prints "subtotal NaN"

const subtotal = cartItems.reduce( (accumulator, { pricePerItem, quantity }) => { return accumulator + pricePerItem * quantity; }, 0 );

Lucas Minter
~ 2 years ago

Here is the link to the finished index page on Colby's GitHub. Check your code against what Colby has and see if there is anything different.