Share a Cart with the Header

Write the code, see it run, pass the checks.

The problem

  • medium
  • Code
  • Pro

A shop's header shows how many items are in the cart, while the product list further down adds them. Share the cart through context. Export a CartProvider component that renders its children, and a useCart hook that returns an object { items, count, add, remove }. items is an array of { name, quantity } objects, in the order each product was first added. add(name) adds one of that product. remove(name) takes one away, drops the product from items when its quantity reaches zero, and does nothing for a product that isn't in the cart. count is the total quantity of everything in the cart. The default export App must use them: a header at the top of the page (not inside main) showing "Cart (N)", where N is count, and a list of Tea, Cake and Jam, each with a button named "Add Tea", "Add Cake" or "Add Jam".

Your code must pass

  • add puts products in the cart for every component
  • remove takes one away and drops products at zero
  • count is the total number of items
  • The header counts what the product list adds