React
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.
Exercise 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.
Show example solution
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;
Test yourself
-
Which hook is NOT used in this lesson?
Three hooks are used; external fetch is not.
- useSWR
- useCart
- useState
- useFetchExternal
Show answer
useFetchExternal — useFetchExternal is not used in this lesson.
-
addItem call
<button onClick={() => ____(product)}>Add to cart</button>
Show answer
<button onClick={() => addItem(product)}>Add to cart</button>
-
Data fetching with SWR: match the terms
- useSWR
- Fetches products
- useCart
- Reads cart
- addItem
- Adds to cart
- isLoading
- Loading state
Next lesson: What is react-hook-form?