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
- Your code has no type errors
- useCart() gives a CartValue you can read without a null check
- useCart() can never be null
- useCart throws an Error when there is no provider
- 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.