#29Shopping cart
45min

Overview

In this challenge, you'll create a simple shopping cart. The goal is to manage the cart’s state globally using context and a provider — allowing users to add, remove, and update products, as well as toggle the cart’s visibility.

Requirements

  • Implement a CartContext that provides global state for the shopping cart.
  • The context should expose:
    • productsInCart: an array containing the products and their quantities.
    • addProductToCart(product): adds a product or increases its quantity if it already exists.
    • removeFromCart(product): removes a product completely from the cart.
    • addQuantity(product): increases the quantity of a product in the cart.
    • removeQuantity(product): decreases the quantity of a product, and removes it if the quantity reaches zero.
    • clearCart(): removes all products from the cart.
    • showCart and setShowCart: controls cart visibility.

Notes

  • Use React Context and TypeScript types to ensure the cart logic is fully typed.
  • Start by defining the CartContextType interface before implementing the provider.
  • Keep the state updates immutable — avoid mutating arrays directly.
  • Use the context directly inside the components — there’s no need to pass any props.
  • Some tests might pass initially because the starter version contains a hardcoded cart with a total.

Tests

  1. renders the app title
  2. renders all products
  3. adds product to cart
  4. increments and decrements product quantity
  5. clears cart
  6. does not duplicate product when added twice
  7. toggles cart visibility
  8. updates cart badge when items are added and removed