Tsallaka zuwa abun ciki
Justice Tech School

Fetching Data

Fetch in an effect, store the result in state and handle loading and error states. Ignore stale responses with a flag.

Example
function Users() {
  const [data, setData] = useState(null);
  useEffect(() => {
    let ignore = false;
    fetch('/api/users').then((r) => r.json()).then((d) => { if (!ignore) setData(d); });
    return () => { ignore = true; };
  }, []);
  if (!data) return <p>Loading...</p>;
  return <p>{data.length} users</p>;
}

Exercise

Parse JSON.

r.()

Quiz Test

Why track an ignore flag?

These free lessons are for learning. Join a full course for projects, mentor feedback and a verified certificate.