Load the user profile card

React · React · beginner · greenfield

Adds the profile card with the full async-state triangle: loading, error-with-retry, and the loaded card. HTTP errors are surfaced by checking `res.ok` (fetch doesn't reject on a 500), and a `cancelled` flag in the effect ignores responses that arrive after unmount. The parent keys the card by user id, so each user gets a fresh mount.

Requirements

Files touched

--- src/components/ProfileCard.jsx
+import { useEffect, useState } from 'react';
+
+export function ProfileCard({ userId }) {
+  const [profile, setProfile] = useState(null);
+  const [status, setStatus] = useState('loading');
+  const [attempt, setAttempt] = useState(0);
+
+  useEffect(() => {
+    let cancelled = false;
+    setStatus('loading');
+    fetch(`/api/users/${encodeURIComponent(userId)}`)
+      .then((res) => {
+        if (!res.ok) {
+          throw new Error(`HTTP ${res.status}`);
+        }
+        return res.json();
+      })
+      .then((data) => {
+        if (!cancelled) {
+          setProfile(data);
+          setStatus('ready');
+        }
+      })
+      .catch(() => {
+        if (!cancelled) {
+          setStatus('error');
+        }
+      });
+    return () => {

Review this PR

React practice