Handling API States

  • This lesson introduces handling API states in React and explains how to manage loading, error, and success states effectively.

  • Handling API States

    Loading State

    Loading state improves user experience.

    Example:

const [loading, setLoading] = useState(true);

{loading && <p>Loading...</p>}
  • Shows feedback while data loads.

    Error Handling

    Errors may occur due to:

    • Network issues

    • Server errors

    • Wrong endpoints

    Example:

const [error, setError] = useState(null);

catch(err) {
  setError("Failed to load data");
}
	
  • Always handle errors gracefully.

    Displaying API Data

    Rendering Fetched Data

    Once data is fetched, display it using .map().

    Example:

users.map(user => (
  <p key={user.id}>{user.name}</p>
));
  • Use keys to improve performance.

    Conditional Rendering

{error && <p>{error}</p>}
{loading ? <p>Loading...</p> : <UserList />}
  • Handles all states cleanly