ReactEffects & dataLesson 35 / 69

Fetching from an API

Code Lab40 min

Fetching from an API

Fetching is an effect plus three states — loading, error, data:

const [state, setState] = useState({ loading: true });

useEffect(() => {
  fetch('/api/lessons')
    .then((r) => r.json())
    .then((data) => setState({ loading: false, data }))
    .catch((error) => setState({ loading: false, error }));
}, []);

The unglamorous truth: fetching well is state management, not the fetch call. Loading spinners and error alerts are the UI users judge you on. In this very app, server components do this fetch before the page even renders — the same three states, moved to a better place.

Exercise

Fetch /roadmaps/fullstack from this app's API and render the course titles. Handle the loading and error states visibly.

Practice this lesson in the IDE

Open the React practice workspace, edit the starter code, and run your work in the browser.

Open IDE and practice