Effective Loading and Error Handling in React Applications

Md Yusuf - Sep 30 - - Dev Community

In React, handling loading and error states is common when dealing with data fetching or asynchronous operations. Here’s a clean way to manage these states using useState and useEffect.

Example: Handling Loading and Error States

import React, { useState, useEffect } from 'react';

function DataFetchingComponent() {
  const [data, setData] = useState(null);
  const [loading, setLoading] = useState(true);  // Loading state
  const [error, setError] = useState(null);      // Error state

  useEffect(() => {
    const fetchData = async () => {
      setLoading(true);
      setError(null); // Reset error before starting the request

      try {
        const response = await fetch('https://api.example.com/data');
        if (!response.ok) {
          throw new Error('Failed to fetch data');  // If response is not OK, handle it
        }
        const result = await response.json();
        setData(result);  // Set data after successful fetch
      } catch (err) {
        setError(err.message);  // Catch any errors and set error state
      } finally {
        setLoading(false);  // Always turn off loading state when done
      }
    };

    fetchData();
  }, []);  // Empty array means it runs once when the component mounts

  if (loading) {
    return <p>Loading...</p>;  // Show loading state
  }

  if (error) {
    return <p>Error: {error}</p>;  // Show error message
  }

  return (
    <div>
      {/* Render the fetched data when available */}
      <h1>Data Fetched Successfully</h1>
      <pre>{JSON.stringify(data, null, 2)}</pre>
    </div>
  );
}

export default DataFetchingComponent;
Enter fullscreen mode Exit fullscreen mode

Key Parts:

  1. State Management:

    • loading: Tracks if the data is still being fetched.
    • error: Stores any errors encountered during the fetch process.
    • data: Holds the fetched data.
  2. Effect Hook:

    • useEffect is used to trigger the fetch when the component mounts.
  3. Error Handling:

    • Uses try...catch to handle any errors during the data fetch.
  4. Conditional Rendering:

    • Based on the state (loading, error, data), different parts of the UI are rendered.

This ensures a user-friendly experience by showing feedback for both loading and error states.

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Terabox Video Player