Skip to content

Checkpoint: Topic of the Moment

The Course
•
30 min study

Close the earlier lessons and build this from the brief. The starter includes the pretend server, src/api.js.

The brief

A box that shows one course topic at a time and moves to the next every two seconds.

  1. Load the topics with fetchTopics. Show Loading… while waiting.
  2. The first attempt must fail, so you can see your error state: pass { fail: true } the first time only. Show Couldn't load the topics. and a Try again button that loads them again.
  3. When loaded, show 1 of 3: Components, with the title in bold. Every 2 seconds, move to the next topic, back to the first after the last.
  4. A Pause button stops the rotation, and its text changes to Resume.

Acceptance checks:

  • The error appears first. Try again shows Loading…, then 1 of 3: Components.
  • After about 2 seconds, 2 of 3: State.
  • While paused, the topic doesn't change.
  • Pausing and resuming several times never makes it go faster.
Your workspace React · 4 files
import { createRoot } from "react-dom/client"; import App from "./App.jsx"; import "./styles.css"; createRoot(document.getElementById("root")).render(<App />); // A pretend server. The lab can't use the network, so these functions wait, // like a real request would, and then return data or fail. const topics = [ { id: 1, title: "Components", summary: "Functions that return JSX." }, { id: 2, title: "State", summary: "A component's memory between renders." }, { id: 3, title: "Effects", summary: "Code that keeps something outside React in step." }, ]; const wait = (ms) => new Promise((resolve) => setTimeout(resolve, ms)); export async function fetchTopics({ fail = false } = {}) { await wait(600); if (fail) throw new Error("The server didn't answer. Try again."); return topics.map(({ id, title }) => ({ id, title })); } // Topic 1 answers slowly and topic 3 quickly, like a real server sometimes does. export async function fetchTopic(id) { await wait(id === 1 ? 1200 : id === 2 ? 600 : 200); const topic = topics.find((t) => t.id === id); if (!topic) throw new Error(`No topic with id ${id}.`); return topic; } // Build the topic carousel here, with fetchTopics from ./api.js. export default function App() { return ( <main> <h1>Topic of the moment</h1> </main> ); } body { font: 16px/1.5 system-ui, sans-serif; margin: 0; color: #1c2430; } main { max-width: 32rem; margin: 1.5rem auto; padding: 0 1rem; } h1 { margin: 0 0 0.75rem; } .card { border: 1px solid #d6dde6; border-radius: 8px; padding: 0.75rem 1rem; margin-bottom: 0.75rem; } .card h2 { margin: 0 0 0.25rem; font-size: 1.1rem; } .muted { color: #6b7785; }
Runs with Vite on your computer: unzip, then npm install and npm run dev.
Hint 1: two effects

One effect loads the data, and runs again when an attempt number changes. A second effect runs the interval, only while the topics are loaded and not paused. Each has its own dependencies and its own cleanup.

Hint 2: one status instead of two flags

A single status state of "loading", "error" or "ready" can be simpler than separate loading and error flags. Exactly one is always true.

Show one solution
One solution React · 4 files
import { createRoot } from "react-dom/client"; import App from "./App.jsx"; import "./styles.css"; createRoot(document.getElementById("root")).render(<App />); // A pretend server. The lab can't use the network, so these functions wait, // like a real request would, and then return data or fail. const topics = [ { id: 1, title: "Components", summary: "Functions that return JSX." }, { id: 2, title: "State", summary: "A component's memory between renders." }, { id: 3, title: "Effects", summary: "Code that keeps something outside React in step." }, ]; const wait = (ms) => new Promise((resolve) => setTimeout(resolve, ms)); export async function fetchTopics({ fail = false } = {}) { await wait(600); if (fail) throw new Error("The server didn't answer. Try again."); return topics.map(({ id, title }) => ({ id, title })); } // Topic 1 answers slowly and topic 3 quickly, like a real server sometimes does. export async function fetchTopic(id) { await wait(id === 1 ? 1200 : id === 2 ? 600 : 200); const topic = topics.find((t) => t.id === id); if (!topic) throw new Error(`No topic with id ${id}.`); return topic; } import { useEffect, useState } from "react"; import { fetchTopics } from "./api.js"; export default function App() { const [topics, setTopics] = useState([]); const [status, setStatus] = useState("loading"); const [attempt, setAttempt] = useState(0); const [index, setIndex] = useState(0); const [paused, setPaused] = useState(false); // Load, and load again whenever Try again bumps the attempt number. useEffect(() => { let ignore = false; setStatus("loading"); // The first attempt fails on purpose, so the error state can be seen. fetchTopics({ fail: attempt === 0 }) .then((data) => { if (ignore) return; setTopics(data); setStatus("ready"); }) .catch(() => { if (!ignore) setStatus("error"); }); return () => { ignore = true; }; }, [attempt]); // Move to the next topic every 2 seconds while ready and not paused. useEffect(() => { if (status !== "ready" || paused) return; const id = setInterval(() => { setIndex((i) => (i + 1) % topics.length); }, 2000); return () => clearInterval(id); }, [status, paused, topics.length]); return ( <main> <h1>Topic of the moment</h1> {status === "loading" && <p>Loading…</p>} {status === "error" && ( <p> Couldn't load the topics. <button onClick={() => setAttempt(attempt + 1)}>Try again</button> </p> )} {status === "ready" && ( <> <p className="card"> {index + 1} of {topics.length}: <strong>{topics[index].title}</strong> </p> <button onClick={() => setPaused(!paused)}>{paused ? "Resume" : "Pause"}</button> </> )} </main> ); } body { font: 16px/1.5 system-ui, sans-serif; margin: 0; color: #1c2430; } main { max-width: 32rem; margin: 1.5rem auto; padding: 0 1rem; } h1 { margin: 0 0 0.75rem; } .card { border: 1px solid #d6dde6; border-radius: 8px; padding: 0.75rem 1rem; margin-bottom: 0.75rem; } .card h2 { margin: 0 0 0.25rem; font-size: 1.1rem; } .muted { color: #6b7785; }
Runs with Vite on your computer: unzip, then npm install and npm run dev.

Check yourself

  1. What does an effect's dependency list mean, and what goes in it?
  2. When does React call an effect's cleanup function?
  3. Two requests for different ids are running. How does the ignore pattern make sure only the latest one updates the page?

Was this article helpful?

Your response is saved on this device.