A very common task in modern web applications.
01
01
Understand the problem
data fetchinguseEffectapiasynchronous
02
02
Attempt it yourself
Sketch your approach before reading the solution — that's what interviews test.
Stuck? AI Nudge Available
Get a conceptual hint to guide your logic without spoiling the final implementation.
03
03
Study the solution
The solution is waiting
Give it an honest attempt first — then compare your thinking with the full walkthrough.
04
04
Read the code
Manual fetch with loading/error/race guard
import { useState, useEffect } from "react";
export default function App() {
const [state, setState] = useState({ loading: true, error: null, data: null });
useEffect(() => {
let ignore = false;
fetch("https://api.example.com/user/1")
.then((res) => { if (!res.ok) throw new Error("HTTP " + res.status); return res.json(); })
.then((data) => { if (!ignore) setState({ loading: false, error: null, data }); })
.catch((error) => { if (!ignore) setState({ loading: false, error, data: null }); });
return () => { ignore = true; }; // discard stale response
}, []);
if (state.loading) return <p>Loading…</p>;
if (state.error) return <p>Error: {state.error.message}</p>;
return <pre style={{ fontFamily: "system-ui" }}>{JSON.stringify(state.data, null, 2)}</pre>;
}05
05
Join the discussion
Discussion (0)
Sign in to join the discussion.
No responses yet. Be the first to share what you think.