CodeBlanks Logo Icon CodeBlanks

Data fetching with SWR

Fetch products with SWR and feed them into the Zustand cart.

Fetching products with SWR

In the final lesson you fetch products with SWR and add them to the Zustand cart. useSWR fetches cached data, and addItem adds to the cart.

This is the core of a real e-commerce flow: fetch data + user interaction + state update. The three parts work together.

SWR's auto retry and refetch-on-focus features guarantee the latest products are added to the cart.

Combining the whole flow

In the final step you combine all pieces: fetch products with useSWR, get addItem with useCart, and put an 'Add to cart' button next to each product.

When the button is clicked addItem(product) fires; Zustand updates the cart; React auto-rerenders. This is the essence of reactive programming.

This structure is the skeleton of a small e-commerce page; it extends easily to real projects.

Practice Product page with cart

Complete the skeleton. Write a ProductPage component. Fetch '/api/products' with useSWR (fetcher: (url) => fetch(url).then(r => r.json())). Get addItem from useCart (selector (s) => s.addItem). If isLoading render <p>Loading</p>. Otherwise render <ul> with products.map(p => <li key={p.id}>{p.name}<button onClick={() => addItem(p)}>Add to cart</button></li>). Add export default.

Starter code

App.jsx
import useSWR from 'swr';
import { useCart } from './useCart';

// Write ProductPage here

Sample solution

App.jsx
import useSWR from 'swr';
import { useCart } from './useCart';

function ProductPage() {
  const { data: products, isLoading } = useSWR(
    '/api/products',
    (url) => fetch(url).then((r) => r.json())
  );
  const addItem = useCart((s) => s.addItem);
  if (isLoading) return <p>Loading</p>;
  return (
    <ul>
      {products.map((p) => (
        <li key={p.id}>
          {p.name}
          <button onClick={() => addItem(p)}>Add to cart</button>
        </li>
      ))}
    </ul>
  );
}

export default ProductPage;

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Which hook is NOT used in this lesson?

App.jsx
Three hooks are used; external fetch is not.
  • useSWR
  • useCart
  • useState
  • useFetchExternal Correct answer

Explanation: useFetchExternal is not used in this lesson.

2 addItem call

Question
<button onClick={() => ____(product)}>Add to cart</button>
Answer
<button onClick={() => addItem(product)}>Add to cart</button>

Explanation: addItem adds the product to the cart.

3 Data fetching with SWR: match the terms

Term Meaning
useSWR Fetches products
useCart Reads cart
addItem Adds to cart
isLoading Loading state

All lessons in Advanced