Command Palette

Search for a command to run...

Hectal
Phase 15: State Management at Scale
React · Exercise 5 of 5 Previous
Advanced

Shop: server state in a query, client state in a store

Build a small shop that uses TanStack Query for the products and Zustand for the client state. fakeFetchProducts(category) is given: it logs GET <category> and resolves after 150 ms.

A Zustand store useShop holds category (starts "tea"), cart (an array of product ids) and actions pick(category) and add(id). Don't store the products in it.

Tabs: two buttons with className="tab", text tea and mugs. <ul id="products"> lists the products of the selected category as <li> items, each with a button className="add". While loading, show <p id="loading">Loading…</p>. <span id="cart-count"> shows the cart size.

Use the category in the query key (["products", category]) with staleTime: 60_000, so returning to a category uses the cache and doesn't fetch again.

What Check tests

  1. The tea products load
  2. Adding a product updates the cart count
  3. The mugs tab shows Loading… and then the mugs
  4. Going back to tea uses the cache (no second GET tea)
  5. The cart survived the tab switches
  6. Products are not copied into the store

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.