CodeBlanks Logo Icon CodeBlanks

Summary - Data fetching

Fetch products with SWR and write an add-to-cart flow.

Summary - Data fetching

In this group you learned cached data fetching with SWR, server state management with React Query, and data mutation with useMutation. Now it's time to combine them.

Typical flow: fetch the product list with useSWR or useQuery; add a new product with useMutation; in onSuccess refresh the cache with invalidateQueries. This loop is the heart of modern React apps.

In the next step you will write a complete flow that fetches products and adds them to a cart.

Practice ProductPage with cart add

Complete the skeleton. Write a ProductPage component. Fetch '/api/products' with useSWR (fetcher: (url) => fetch(url).then(r => r.json())). If isLoading render <p>Loading</p>. Otherwise render <ul> with products.map(p => <li key={p.id}>{p.name}<button onClick={() => addToCart(p)}>Add to cart</button></li>). Define addToCart taking a product parameter and calling console.log. Add export default.

Starter code

App.jsx
import useSWR from 'swr';

// Write ProductPage here

Sample solution

App.jsx
import useSWR from 'swr';

function addToCart(product) {
  console.log('Added to cart:', product.name);
}

function ProductPage() {
  const { data: products, isLoading } = useSWR(
    '/api/products',
    (url) => fetch(url).then((r) => r.json())
  );
  if (isLoading) return <p>Loading</p>;
  return (
    <ul>
      {products.map((p) => (
        <li key={p.id}>
          {p.name}
          <button onClick={() => addToCart(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 topic was NOT covered in this group?

App.jsx
Three topics were covered; router was not.
  • Fetching with SWR
  • React Query useQuery
  • Changing data with useMutation
  • Router configuration Correct answer

Explanation: Router was not covered in this group.

2 invalidateQueries call

Question
queryClient.____({ queryKey: ['products'] });
Answer
queryClient.invalidateQueries({ queryKey: ['products'] });

Explanation: invalidateQueries refreshes the cache.

All lessons in Advanced