Command Palette

Search for a command to run...

Hectal
Phase 14: TypeScript with React
TypeScript · Exercise 4 of 6 PreviousNext
Intermediate

A cart context with a guard hook

Two components read a shared cart count. Make the context hold CartValue | null, then make useCart() return a CartValue (never null) and throw an Error when it is used outside <CartProvider>.

The checks use the names useCart, CartValue and the ids #add and #count.

What Check tests

  1. Your code has no type errors
  2. useCart() gives a CartValue you can read without a null check
  3. useCart() can never be null
  4. useCart throws an Error when there is no provider
  5. Both components share the cart: two clicks show 2

Stuck? One hint at a time

The solution unlocks after your first Check. Try first: that is where the learning happens.

Runs in your browser. Your code is saved here.

Your page

Press Run to see the page.

Console

Nothing logged yet.