Problem Solving: Shopping Cart using Redux

I’m building an e-commerce project using the Fake Store API. This API contains 20 items that include the item’s title, description, price, and category. I wanted the user to experience modern e-commerce with features such as add items to cart and modify its quantities.

At first I was adding a product they selected into a new array. I, then, mapped through the new array to display items in the checkout page.

The problem emerged when the user wanted to purchase multiple quantities of the same product. The current implementation made it so that when a user adds the same item, a duplicate item would be added to the new array. I would then have to find duplicates of the item, calculate how many there are, and display that number in the checkout page. It started to feel too complex and intricate as I would have to use two iterators to find duplicates and do complex filtering. I knew there had to be a simpler way.

I took a break and walked around the neighborhood, keeping the problem in mind. What I realized is that I could add a boolean of “inCart” and an integer of “qty” to each individual item from the Fake Store API response.

Then, every time the user wanted to add a product to the new array, the application would just have to update “inCart” to true and qty to qty + 1.

Then, I can map through the original array, and display the item and its quantity only if the product’s “inCart” property is true.

This single source of truth made developing the rest of the app easy. Remove From Cart, Add Qty, and Subtract Qty was easier to implement.

Knowing when to take a break is a valuable lesson I learn again and again.

See the project here:

Have you made an e-commerce project using the Fake Store API? How did you implement the cart quantity feature?

I’m a web developer currently looking for an opportunity to contribute to a team! Are you looking for a motivated developer? Contact me!