Sequence NODE_190
MediumFetch Data with Loading & Error States
React
JavaScript
Technical Specification
Build a component that fetches data from an API and shows loading, error, or data UI.
Input/Output Samples
Input:Component mounts
Output:Shows loading then data or error
Optimal Logic Path
import { useState, useEffect } from "react";
function UsersList() {
const [users, setUsers] = useState([]);
const [status, setStatus] = useState("idle"); // idle | loading | error | success
const [error, setError] = useState("");
useEffect(() => {
async function load() {
setStatus("loading");
try {
const res = await fetch("https://jsonplaceholder.typicode.com/users");
if (!res.ok) throw new Error("Failed to load");
const data = await res.json();
setUsers(data);
setStatus("success");
} catch (err) {
setError(err.message || "Unknown error");
setStatus("error");
}
}
load();
}, []);
if (status === "loading") return <p>Loading...</p>;
if (status === "error") return <p>Error: {error}</p>;
return (
<ul>
{users.map((u) => (
<li key={u.id}>{u.name}</li>
))}
</ul>
);
}Architectural Deep-Dive
We use a small state machine for status and show different UI based on loading, error, or success.