#29Shopping cart
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.showCartandsetShowCart: controls cart visibility.
Notes
- Use React Context and TypeScript types to ensure the cart logic is fully typed.
- Start by defining the
CartContextTypeinterface 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
- renders the app title
- renders all products
- adds product to cart
- increments and decrements product quantity
- clears cart
- does not duplicate product when added twice
- toggles cart visibility
- updates cart badge when items are added and removed