Menu

Handling Loading and Error States

Handling Loading and Error States

Why This Matters

An API call has three possible states, and a good interface handles all three: loading, success, and error. Beginners handle only success, which produces blank screens on slow connections and silent failures when the server is down.

Example

src/components/CourseDashboard.jsx

jsx

import { useState, useEffect } from "react";

function CourseDashboard() {
  const [courses, setCourses] = useState([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);

  useEffect(() => {
    async function loadCourses() {
      try {
        setLoading(true);
        setError(null);

        const response = await fetch("https://jsonplaceholder.typicode.com/posts");

        if (!response.ok) {
          throw new Error("Could not load courses. Please try again.");
        }

        const data = await response.json();
        setCourses(data.slice(0, 6));
      } catch (err) {
        setError(err.message);
      } finally {
        setLoading(false);
      }
    }

    loadCourses();
  }, []);

  if (loading) {
    return <p>Loading your courses...</p>;
  }

  if (error) {
    return (
      <div className="error">
        <p>{error}</p>
        <button onClick={() => window.location.reload()}>Retry</button>
      </div>
    );
  }

if (courses.length === 0) {

return <p>You have not enrolled in any courses yet.</p>;

}

return (

<ul>

{courses.map(course => (

<li key={course.id}>{course.title}</li>

))}

</ul>

);

}

export default CourseDashboard;

How It Works

  • Three pieces of state track the three possible situations.
  • try holds the code that might fail, catch handles failure, finally runs either way — which is exactly where setLoading(false) belongs.
  • if (!response.ok) throw new Error(...) converts an HTTP error status into a real error, since fetch() will not do it for you.
  • The four early returns handle loading, error, empty, and success in order. This reads far better than nesting ternaries in the JSX.

The empty state matters. A successful response with zero results is not an error, and showing a blank area confuses users.

Output

A loading message, then either the course list, a friendly error with a retry button, or an empty-state message.


ReactJS Tutorial

VA

Vishalini A



Learn via Video Course

React.js for Beginners: Build Modern Web Applications with React Logo

React.js for Beginners: Build Modern Web Applications with React

6 hrs



Get in Touch For Details