AI Hints
Home›React Tutorial›Fetching Data
React · Lesson 40 of 120

Fetching Data

Loading and errors.

⏱ 2 min read▶ Video at 31:41🎓 Free
Watch this lesson in the React courseWatch on YouTube ↗Full React course

Most apps load data from a server. In this course, a small file called api dot j s stands in for a real server. It returns our products after a short delay, just like fetch would.

  • Data from a server
  • api.js stands in
  • Short delay

Loading products

We keep three pieces of state. The products, a loading flag, and an error. The effect calls get products once, and stores the result, or the error. While loading, we show a message. Run it. After the delay, the list appears.

App.jsxjsx
import { useState, useEffect } from "react";
import { getProducts } from "./api";
export default function App() {
  const [products, setProducts] = useState([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);
  useEffect(() => {
    getProducts()
      .then(setProducts)
      .catch(err => setError(err.message))
      .finally(() => setLoading(false));
  }, []);
  if (loading) return <p>Loading products...</p>;
  if (error) return <small>{error}</small>;
  return <ul>{products.map(p => <li key={p.id}>{p.name} — £{p.price}</li>)}</ul>;
}
Also uses style.css
body{font-family:-apple-system,Helvetica,Arial,sans-serif;margin:22px;font-size:21px;color:#1d1d1f;background:#fafafa}
h1{font-size:34px;margin:0 0 14px} h2{font-size:26px;margin:0 0 10px}
button{font-size:19px;padding:9px 18px;border-radius:9px;border:0;background:#61dafb;color:#111;font-weight:600;margin:4px 6px 4px 0}
input{font-size:19px;padding:8px 10px;border:2px solid #bbb;border-radius:8px}
li{margin:5px 0} .box{padding:14px;border-radius:12px;background:#fff;border:2px solid #ddd;margin:8px 0}
.done{text-decoration:line-through;color:#999} small{color:crimson;display:block;font-size:16px} .big{font-size:64px;font-weight:800}
Also uses api.js
const PRODUCTS = [
  { id: 1, name: "Trail 500", price: 849.5, type: "bike", stock: 12 },
  { id: 2, name: "City 200", price: 450, type: "bike", stock: 0 },
  { id: 3, name: "Volt 7", price: 2199, type: "bike", stock: 4 },
  { id: 4, name: "Helmet", price: 40, type: "gear", stock: 30 },
  { id: 5, name: "Lights", price: 25, type: "gear", stock: 18 },
];
const wait = ms => new Promise(resolve => setTimeout(resolve, ms));

export async function getProducts() {
  await wait(300);
  return PRODUCTS;
}

export async function getProduct(id) {
  await wait(300);
  const product = PRODUCTS.find(p => p.id === Number(id));
  if (!product) throw new Error(`Product ${id} not found`);
  return product;
}
Also uses actions.json
[{"wait": 600}]

Three states

Every fetch has three states. Loading, while you wait. Success, when the data arrives. Or error, when something went wrong. Show something useful for each one.

  1. Loading
  2. Success
  3. Error

Summary

Fetch in an effect, and track loading, data, and errors in state. Next, race conditions.

Key takeaways
  • useEffect + fetch
  • loading
  • error
Next up: Race Conditions — ignore old results