JavaScript and React course ยท Module 5: useEffect and Custom Hooks

API Handling and Data Fetching

15 min read ยท
In this lesson6

Communicating with external APIs is one of the most common use cases for side effects in React applications. In this module, we'll learn how to efficiently fetch, process, and manage data from external sources.

Basics of fetching data from an API

In web applications, data often comes from external APIs that provide information in JSON, XML, or other formats. On our cosmic journey, we can imagine a mission control center fetching data from various satellites, spaceships, and research stations.

Simple example of fetching data with useEffect

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

function AstronautsList() {
  const [astronauts, setAstronauts] = useState([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);

  useEffect(() => {
    // Async function for fetching data
    async function fetchAstronauts() {
      try {
        setLoading(true);
        // Fetching data
        const response = await fetch('https://api.spaceagency.com/astronauts');

        // Check if response is OK
        if (!response.ok) {
          throw new Error(`HTTP Error: ${response.status}`);
        }

        // Parse JSON response
        const data = await response.json();

        // Update state
        setAstronauts(data);
        setError(null);
      } catch (err) {
        // Error handling
        setError(`Failed to fetch data: ${err.message}`);
        setAstronauts([]);
      } finally {
        // Mark loading as complete
        setLoading(false);
      }
    }

    // Call the function
    fetchAstronauts();
  }, []); // Empty dependency array - execute only once

  // Render based on state
  if (loading) return <div>Loading data...</div>;
  if (error) return <div>Error: {error}</div>;

  return (
    <div>
      <h2>Active Astronauts</h2>
      <ul>
        {astronauts.map(astronaut => (
          <li key={astronaut.id}>
            {astronaut.name} - {astronaut.role}
          </li>
        ))}
      </ul>
    </div>
  );
}

In the example above:

  1. We use useState to store data, loading state, and errors
  2. We use useEffect with an empty dependency array to fetch data only once after mounting
  3. We use async/await to handle asynchronous data fetching
  4. We handle different states (loading, error, success) in the user interface

Advanced data fetching techniques

1. Fetching data with parameters

Often we need to fetch data based on parameters that can change:

function MissionDetails({ missionId }) {
  const [mission, setMission] = useState(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);

  useEffect(() => {
    let isMounted = true; // Flag to prevent state updates after unmount

    async function fetchMission() {
      try {
        setLoading(true);

        const response = await fetch(
          `https://api.spaceagency.com/missions/${missionId}`
        );

        if (!response.ok) {
          throw new Error(`HTTP Error: ${response.status}`);
        }

        const data = await response.json();

        // Update state only if component is still mounted
        if (isMounted) {
          setMission(data);
          setError(null);
        }
      } catch (err) {
        if (isMounted) {
          setError(`Failed to fetch mission data: ${err.message}`);
          setMission(null);
        }
      } finally {
        if (isMounted) {
          setLoading(false);
        }
      }
    }

    fetchMission();

    // Cleanup function
    return () => {
      isMounted = false; // Mark that the component has been unmounted
    };
  }, [missionId]); // Refetch data when missionId changes

  // Rendering
  if (loading) return <div>Loading mission data...</div>;
  if (error) return <div>Error: {error}</div>;
  if (!mission) return <div>Mission not found</div>;

  return (
    <div className="mission-details">
      <h2>{mission.name}</h2>
      <p>Status: {mission.status}</p>
      <p>Launch date: {new Date(mission.launchDate).toLocaleDateString()}</p>
      <p>Commander: {mission.commander}</p>
      {/* More mission details */}
    </div>
  );
}

In this example:

  1. We fetch data based on missionId, which can change
  2. We use an isMounted flag to prevent state updates after unmount
  3. We add a cleanup function that sets isMounted = false on unmount

2. Canceling fetch requests

The Fetch API doesn't have a built-in cancellation mechanism, but we can use AbortController to abort a request:

function SpaceWeather({ location }) {
  const [weatherData, setWeatherData] = useState(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);

  useEffect(() => {
    // Create AbortController to cancel the request
    const abortController = new AbortController();
    const signal = abortController.signal;

    async function fetchWeatherData() {
      try {
        setLoading(true);

        const response = await fetch(
          `https://api.spaceagency.com/weather/${location}`,
          { signal } // Assign signal to the request
        );

        if (!response.ok) {
          throw new Error(`HTTP Error: ${response.status}`);
        }

        const data = await response.json();
        setWeatherData(data);
        setError(null);
      } catch (err) {
        // Ignore cancellation errors
        if (err.name === 'AbortError') {
          console.log('Weather request was cancelled');
        } else {
          setError(`Failed to fetch weather data: ${err.message}`);
          setWeatherData(null);
        }
      } finally {
        setLoading(false);
      }
    }

    fetchWeatherData();

    // Cleanup function cancels the request if the component
    // is unmounted before fetching completes
    return () => {
      abortController.abort();
    };
  }, [location]);

  // Rendering
  if (loading) return <div>Loading weather data...</div>;
  if (error) return <div>Error: {error}</div>;
  if (!weatherData) return <div>No weather data available</div>;

  return (
    <div className="space-weather">
      <h2>Space Weather: {location}</h2>
      <p>Radiation: {weatherData.radiation} mSv</p>
      <p>Solar activity: {weatherData.solarActivity}</p>
      <p>Temperature: {weatherData.temperature}ยฐC</p>
    </div>
  );
}

In this example:

  1. We use AbortController to create a signal that can abort a Fetch request
  2. We pass the signal to the Fetch request options
  3. In the cleanup function, we call abortController.abort() to cancel an ongoing request
  4. We specifically handle the AbortError that is thrown when a request is cancelled

3. Handling multiple concurrent requests

Sometimes we need to fetch data from several sources simultaneously:

function MissionDashboard({ missionId }) {
  const [missionData, setMissionData] = useState({
    details: null,
    crew: [],
    telemetry: null
  });
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);

  useEffect(() => {
    let isMounted = true;

    async function fetchMissionData() {
      try {
        setLoading(true);

        // Fetch data in parallel using Promise.all
        const [detailsResponse, crewResponse, telemetryResponse] = await Promise.all([
          fetch(`https://api.spaceagency.com/missions/${missionId}`),
          fetch(`https://api.spaceagency.com/missions/${missionId}/crew`),
          fetch(`https://api.spaceagency.com/missions/${missionId}/telemetry`)
        ]);

        // Check responses
        if (!detailsResponse.ok || !crewResponse.ok || !telemetryResponse.ok) {
          throw new Error('One or more requests failed');
        }

        // Parse data in parallel
        const [details, crew, telemetry] = await Promise.all([
          detailsResponse.json(),
          crewResponse.json(),
          telemetryResponse.json()
        ]);

        if (isMounted) {
          setMissionData({ details, crew, telemetry });
          setError(null);
        }
      } catch (err) {
        if (isMounted) {
          setError(`Failed to fetch mission data: ${err.message}`);
        }
      } finally {
        if (isMounted) {
          setLoading(false);
        }
      }
    }

    fetchMissionData();

    return () => {
      isMounted = false;
    };
  }, [missionId]);

  // Rendering
  if (loading) return <div>Loading mission data...</div>;
  if (error) return <div>Error: {error}</div>;

  const { details, crew, telemetry } = missionData;

  return (
    <div className="mission-dashboard">
      <h1>{details.name} - Control Panel</h1>

      <section className="mission-details">
        <h2>Mission Details</h2>
        <p>Status: {details.status}</p>
        <p>Objective: {details.objective}</p>
      </section>

      <section className="crew-info">
        <h2>Crew</h2>
        <ul>
          {crew.map(member => (
            <li key={member.id}>
              {member.name} - {member.role}
            </li>
          ))}
        </ul>
      </section>

      <section className="telemetry-data">
        <h2>Telemetry</h2>
        <p>Oxygen: {telemetry.oxygen}%</p>
        <p>Fuel: {telemetry.fuel}%</p>
        <p>Velocity: {telemetry.velocity} km/h</p>
      </section>
    </div>
  );
}

In this example:

  1. We use Promise.all() for parallel execution of multiple requests
  2. We gather all data in a single missionData state
  3. We handle all data in one component

Best practices and patterns

1. Extracting data fetching logic

To improve readability and code maintenance, it's worth extracting the data fetching logic outside the component:

// api.js - API Services
const API_BASE_URL = 'https://api.spaceagency.com';

export async function fetchAstronauts() {
  const response = await fetch(`${API_BASE_URL}/astronauts`);
  if (!response.ok) {
    throw new Error(`HTTP Error: ${response.status}`);
  }
  return response.json();
}

export async function fetchMission(missionId) {
  const response = await fetch(`${API_BASE_URL}/missions/${missionId}`);
  if (!response.ok) {
    throw new Error(`HTTP Error: ${response.status}`);
  }
  return response.json();
}

// Component with extracted API logic
function AstronautsList() {
  const [astronauts, setAstronauts] = useState([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);

  useEffect(() => {
    let isMounted = true;

    async function getAstronauts() {
      try {
        setLoading(true);
        const data = await fetchAstronauts();

        if (isMounted) {
          setAstronauts(data);
          setError(null);
        }
      } catch (err) {
        if (isMounted) {
          setError(`Failed to fetch data: ${err.message}`);
          setAstronauts([]);
        }
      } finally {
        if (isMounted) {
          setLoading(false);
        }
      }
    }

    getAstronauts();

    return () => {
      isMounted = false;
    };
  }, []);

  // Rendering
  //
}

2. Creating custom hooks for data fetching

For repeatable data fetching operations, the best solution is to create a custom hook:

// useFetch.js - Custom hook for data fetching
function useFetch(url, options = {}) {
  const [data, setData] = useState(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);

  useEffect(() => {
    let isMounted = true;
    const abortController = new AbortController();
    const signal = abortController.signal;

    async function fetchData() {
      try {
        setLoading(true);

        const response = await fetch(url, {
          ...options,
          signal,
        });

        if (!response.ok) {
          throw new Error(`HTTP Error: ${response.status}`);
        }

        const result = await response.json();

        if (isMounted) {
          setData(result);
          setError(null);
        }
      } catch (err) {
        if (err.name !== 'AbortError' && isMounted) {
          setError(`Failed to fetch data: ${err.message}`);
          setData(null);
        }
      } finally {
        if (isMounted) {
          setLoading(false);
        }
      }
    }

    fetchData();

    return () => {
      isMounted = false;
      abortController.abort();
    };
  }, [url, JSON.stringify(options)]);

  return { data, loading, error };
}

// Using the custom hook
function PlanetInfo({ planetId }) {
  const { data: planet, loading, error } = useFetch(
    `https://api.spaceagency.com/planets/${planetId}`
  );

  if (loading) return <div>Loading...</div>;
  if (error) return <div>Error: {error}</div>;
  if (!planet) return <div>Planet not found</div>;

  return (
    <div className="planet-card">
      <h2>{planet.name}</h2>
      <p>Type: {planet.type}</p>
      <p>Diameter: {planet.diameter} km</p>
      <p>Distance from Sun: {planet.distanceFromSun} million km</p>
    </div>
  );
}

3. More advanced data fetching hook with caching and retry mechanism

// useDataFetching.js
function useDataFetching(fetchFn, dependencies = [], options = {}) {
  const {
    initialData = null,
    cacheKey = null,
    maxRetries = 3,
    retryDelay = 1000,
  } = options;

  const [data, setData] = useState(initialData);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);

  // Using useRef to track attempts
  const retriesRef = useRef(0);

  // Check cache on first render
  useEffect(() => {
    if (cacheKey) {
      const cachedData = localStorage.getItem(cacheKey);
      if (cachedData) {
        try {
          setData(JSON.parse(cachedData));
          setLoading(false);
        } catch (e) {
          console.error('Error parsing cached data:', e);
        }
      }
    }
  }, [cacheKey]);

  // Main data fetching logic
  useEffect(() => {
    let isMounted = true;
    const abortController = new AbortController();

    async function fetchData() {
      try {
        setLoading(true);

        const result = await fetchFn(abortController.signal);

        if (isMounted) {
          setData(result);
          setError(null);

          // Save to cache if available
          if (cacheKey) {
            localStorage.setItem(cacheKey, JSON.stringify(result));
          }

          // Reset retry counter
          retriesRef.current = 0;
        }
      } catch (err) {
        if (!isMounted) return;

        if (err.name === 'AbortError') {
          console.log('Request cancelled');
          return;
        }

        // Retry logic
        if (retriesRef.current < maxRetries) {
          console.log(`Attempt ${retriesRef.current + 1} of ${maxRetries} failed. Retrying in ${retryDelay}ms`);

          setTimeout(() => {
            if (isMounted) {
              retriesRef.current += 1;
              fetchData(); // Retry
            }
          }, retryDelay * Math.pow(2, retriesRef.current)); // Exponential backoff

          return;
        }

        // After exhausting all attempts
        setError(`Failed to fetch data: ${err.message}`);
        setData(initialData);
      } finally {
        if (isMounted) {
          setLoading(false);
        }
      }
    }

    fetchData();

    return () => {
      isMounted = false;
      abortController.abort();
    };
  }, [...dependencies]);

  // Function for manual data refresh
  const refetch = useCallback(async () => {
    setLoading(true);
    retriesRef.current = 0;

    try {
      const abortController = new AbortController();
      const result = await fetchFn(abortController.signal);
      setData(result);
      setError(null);

      if (cacheKey) {
        localStorage.setItem(cacheKey, JSON.stringify(result));
      }
    } catch (err) {
      setError(`Failed to refresh data: ${err.message}`);
    } finally {
      setLoading(false);
    }
  }, [fetchFn, cacheKey]);

  return { data, loading, error, refetch };
}

// Usage example
function MarsMissions() {
  // Function to fetch data
  const fetchMissions = useCallback(async (signal) => {
    const response = await fetch('https://api.spaceagency.com/mars/missions', { signal });
    if (!response.ok) throw new Error(`HTTP Error: ${response.status}`);
    return response.json();
  }, []);

  // Using the advanced hook
  const {
    data: missions,
    loading,
    error,
    refetch
  } = useDataFetching(fetchMissions, [], {
    initialData: [],
    cacheKey: 'mars-missions-cache',
    maxRetries: 2
  });

  return (
    <div className="mars-missions">
      <div className="header">
        <h2>Mars Missions</h2>
        <button onClick={refetch} disabled={loading}>
          {loading ? 'Refreshing...' : 'Refresh'}
        </button>
      </div>

      {loading && missions.length === 0 && <div>Loading missions...</div>}
      {error && <div className="error">Error: {error}</div>}

      <ul className="missions-list">
        {missions.map(mission => (
          <li key={mission.id} className={`mission-item ${mission.status}`}>
            <h3>{mission.name}</h3>
            <p>Launch: {new Date(mission.launchDate).toLocaleDateString()}</p>
            <p>Status: {mission.status}</p>
          </li>
        ))}
      </ul>

      {missions.length === 0 && !loading && !error && (
        <p>No missions found.</p>
      )}
    </div>
  );
}

In this advanced example:

  1. We use a custom useDataFetching hook with retry support, caching, and manual refresh functionality
  2. We implement exponential backoff for retries (each subsequent attempt waits longer)
  3. We use parameters to customize hook behavior for different use cases
  4. We handle both initial loading and manual data refresh

Error handling when fetching data

Beyond basic error handling in components, it's worth implementing more advanced techniques:

1. Error Boundary component

Error boundaries allow elegant handling of unexpected errors:

// ErrorBoundary.js
class ErrorBoundary extends React.Component {
  constructor(props) {
    super(props);
    this.state = { hasError: false, error: null, errorInfo: null };
  }

  static getDerivedStateFromError(error) {
    // Update state so next render shows fallback UI
    return { hasError: true };
  }

  componentDidCatch(error, errorInfo) {
    // You can also log the error to a monitoring service
    console.error('Caught error:', error, errorInfo);
    this.setState({ error, errorInfo });

    // Send error to reporting service
    // logErrorToService(error, errorInfo);
  }

  render() {
    if (this.state.hasError) {
      // You can render any fallback UI
      return (
        <div className="error-boundary">
          <h2>Something went wrong!</h2>
          <p>An error occurred while rendering the component.</p>
          <details>
            <summary>Error details</summary>
            <p>{this.state.error && this.state.error.toString()}</p>
            <p>Components: {this.state.errorInfo && this.state.errorInfo.componentStack}</p>
          </details>
          <button onClick={() => this.setState({ hasError: false })}>
            Try again
          </button>
        </div>
      );
    }

    return this.props.children;
  }
}

// Using error boundary for a component
function App() {
  return (
    <div className="app">
      <header>Mission Control Center</header>

      <ErrorBoundary>
        <MissionDashboard missionId="mars-2030" />
      </ErrorBoundary>

      <ErrorBoundary>
        <AstronautsList />
      </ErrorBoundary>

      <footer>Space Agency ยฉ 2023</footer>
    </div>
  );
}

2. Retry strategies

When an API is unstable, it's worth implementing automatic retry strategies:

async function fetchWithRetry(url, options = {}, maxRetries = 3, delay = 1000) {
  let retries = 0;

  while (retries < maxRetries) {
    try {
      const response = await fetch(url, options);

      if (!response.ok) {
        throw new Error(`HTTP Error: ${response.status}`);
      }

      return await response.json();
    } catch (err) {
      retries++;

      if (retries >= maxRetries) {
        throw err; // All attempts failed, pass error forward
      }

      console.log(`Attempt ${retries} of ${maxRetries} failed. Retrying in ${delay}ms`);

      // Wait before next attempt (exponential backoff)
      await new Promise(resolve => setTimeout(resolve, delay * Math.pow(2, retries - 1)));
    }
  }
}

3. Handling connectivity issues

It's also worth handling internet connectivity issues:

// Hook for monitoring connection status
function useOnlineStatus() {
  const [isOnline, setIsOnline] = useState(navigator.onLine);

  useEffect(() => {
    function handleOnline() {
      setIsOnline(true);
    }

    function handleOffline() {
      setIsOnline(false);
    }

    window.addEventListener('online', handleOnline);
    window.addEventListener('offline', handleOffline);

    return () => {
      window.removeEventListener('online', handleOnline);
      window.removeEventListener('offline', handleOffline);
    };
  }, []);

  return isOnline;
}

// Usage in a component
function DataFetchingComponent() {
  const isOnline = useOnlineStatus();
  const { data, loading, error, refetch } = useFetch('https://api.example.com/data');

  if (!isOnline) {
    return (
      <div className="offline-message">
        <h3>No internet connection</h3>
        <p>Check your connection and try again.</p>
      </div>
    );
  }

  if (loading) return <div>Loading...</div>;
  if (error) return <div>Error: {error}</div>;

  return (
    <div>
      <h2>Data</h2>
      {/* Rendering data */}
    </div>
  );
}

API simulation during development

During application development, the real API may be unavailable or not ready. In such cases, it's worth simulating the API:

1. Simple simulation with delay

// mockApi.js
const DELAY = 1000; // Simulating network delay

export function mockFetch(data, shouldFail = false, failureRate = 0) {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      // Simulating random error
      if (shouldFail || Math.random() < failureRate) {
        reject(new Error('Simulated API error'));
        return;
      }

      resolve(data);
    }, DELAY);
  });
}

// Sample data
const MOCK_ASTRONAUTS = [
  { id: 1, name: 'John Smith', role: 'Commander' },
  { id: 2, name: 'Anna Johnson', role: 'Pilot' },
  { id: 3, name: 'Peter Williams', role: 'Flight Engineer' }
];

export function getAstronauts() {
  return mockFetch(MOCK_ASTRONAUTS, false, 0.2);
}

2. More sophisticated simulation with MSW (Mock Service Worker)

MSW is a library that simulates API requests at the browser level:

// mockServiceWorker.js
import { setupWorker, rest } from 'msw';

// Simulation data
const astronauts = [
  { id: 1, name: 'John Smith', role: 'Commander' },
  { id: 2, name: 'Anna Johnson', role: 'Pilot' },
  { id: 3, name: 'Peter Williams', role: 'Flight Engineer' }
];

const missions = [
  {
    id: 'mars-2030',
    name: 'Mars 2030',
    status: 'Planned',
    launchDate: '2030-05-15',
    commander: 'John Smith'
  },
  {
    id: 'iss-2023',
    name: 'ISS Expedition 70',
    status: 'In Progress',
    launchDate: '2023-09-01',
    commander: 'Anna Johnson'
  }
];

// Defining handlers
export const handlers = [
  // Fetching all astronauts
  rest.get('https://api.spaceagency.com/astronauts', (req, res, ctx) => {
    return res(
      ctx.delay(1000),
      ctx.status(200),
      ctx.json(astronauts)
    );
  }),

  // Fetching astronaut by ID
  rest.get('https://api.spaceagency.com/astronauts/:id', (req, res, ctx) => {
    const { id } = req.params;
    const astronaut = astronauts.find(a => a.id === parseInt(id));

    if (!astronaut) {
      return res(
        ctx.delay(500),
        ctx.status(404),
        ctx.json({ error: 'Astronaut not found' })
      );
    }

    return res(
      ctx.delay(500),
      ctx.status(200),
      ctx.json(astronaut)
    );
  }),

  // Fetching missions
  rest.get('https://api.spaceagency.com/missions', (req, res, ctx) => {
    return res(
      ctx.delay(800),
      ctx.status(200),
      ctx.json(missions)
    );
  }),

  // Fetching mission by ID
  rest.get('https://api.spaceagency.com/missions/:id', (req, res, ctx) => {
    const { id } = req.params;
    const mission = missions.find(m => m.id === id);

    if (!mission) {
      return res(
        ctx.delay(500),
        ctx.status(404),
        ctx.json({ error: 'Mission not found' })
      );
    }

    return res(
      ctx.delay(700),
      ctx.status(200),
      ctx.json(mission)
    );
  })
];

// Initialize service worker
export const worker = setupWorker(...handlers);

Then in your application's entry file (e.g., index.js):

// index.js
import React from 'react';
import { createRoot } from 'react-dom/client';
import App from './App';

// Conditionally initialize mock API only in development environment
if (process.env.NODE_ENV === 'development') {
  const { worker } = require('./mockServiceWorker');
  worker.start();
}

const root = createRoot(document.getElementById('root'));
root.render(<App />);

Summary

Fetching data from APIs is a fundamental part of most React applications. The key to success is:

  1. Code organization - separating API logic from components
  2. Custom hooks - creating abstractions for repeatable data fetching operations
  3. Handling all states - loading, success, error, offline
  4. Resource cleanup - canceling requests, preventing state updates after unmount
  5. Retry strategies - automatically retrying failed requests
  6. Testing - simulating APIs during development and tests

Remember that good data fetching handling significantly impacts user experience. Even if the API is slow, a well-designed interface with loading state information, animations, and error handling can make the application feel faster and more reliable.

Code for this lesson: App.jsx
import React, { useState, useEffect } from 'react';

// Custom hook for fetching data
function useFetch(url, options = {}) {
  const [data, setData] = useState(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);

  useEffect(() => {
    const controller = new AbortController();

    const fetchData = async () => {
      setLoading(true);
      setError(null);

      try {
        // Simulating network delay
        await new Promise(resolve => setTimeout(resolve, 1500));

        // Simulating data from the API
        const mockData = getMockData(url);
        setData(mockData);
      } catch (err) {
        if (err.name !== 'AbortError') {
          setError(err.message);
        }
      } finally {
        setLoading(false);
      }
    };

    fetchData();

    // Cleanup - canceling the request
    return () => controller.abort();
  }, [url]);

  return { data, loading, error };
}

// Simulating an API response
function getMockData(url) {
  const endpoints = {
    '/api/planets': [
      { id: 1, name: 'Mars', distance: '225M km', status: 'Colonization' },
      { id: 2, name: 'Jupiter', distance: '628M km', status: 'Exploration' },
      { id: 3, name: 'Saturn', distance: '1.2B km', status: 'Observation' },
      { id: 4, name: 'Uranus', distance: '2.7B km', status: 'Planning' },
    ],
    '/api/missions': [
      { id: 1, name: 'Apollo 25', crew: 6, status: 'In progress' },
      { id: 2, name: 'Artemis 12', crew: 4, status: 'Preparation' },
      { id: 3, name: 'Europa Clipper', crew: 0, status: 'Automatic' },
    ],
    '/api/astronauts': [
      { id: 1, name: 'Anna Kowalska', role: 'Captain', missions: 5 },
      { id: 2, name: 'Jan Nowak', role: 'Engineer', missions: 3 },
      { id: 3, name: 'Maria Wisniewska', role: 'Scientist', missions: 7 },
    ],
  };
  return endpoints[url] || [];
}

// Component displaying planets
function PlanetsList() {
  const { data, loading, error } = useFetch('/api/planets');

  if (loading) return <div className="loading">Loading planets...</div>;
  if (error) return <div className="error">Error: {error}</div>;

  return (
    <div className="data-card">
      <h2>Planets</h2>
      <ul>
        {data?.map(planet => (
          <li key={planet.id}>
            <strong>{planet.name}</strong>
            <span className="detail">Distance: {planet.distance}</span>
            <span className="status">{planet.status}</span>
          </li>
        ))}
      </ul>
    </div>
  );
}

// Component displaying missions
function MissionsList() {
  const { data, loading, error } = useFetch('/api/missions');

  if (loading) return <div className="loading">Loading missions...</div>;
  if (error) return <div className="error">Error: {error}</div>;

  return (
    <div className="data-card">
      <h2>Missions</h2>
      <ul>
        {data?.map(mission => (
          <li key={mission.id}>
            <strong>{mission.name}</strong>
            <span className="detail">Crew: {mission.crew}</span>
            <span className="status">{mission.status}</span>
          </li>
        ))}
      </ul>
    </div>
  );
}

// Component displaying astronauts
function AstronautsList() {
  const { data, loading, error } = useFetch('/api/astronauts');

  if (loading) return <div className="loading">Loading astronauts...</div>;
  if (error) return <div className="error">Error: {error}</div>;

  return (
    <div className="data-card">
      <h2>Astronauts</h2>
      <ul>
        {data?.map(astronaut => (
          <li key={astronaut.id}>
            <strong>{astronaut.name}</strong>
            <span className="detail">Role: {astronaut.role}</span>
            <span className="status">Missions: {astronaut.missions}</span>
          </li>
        ))}
      </ul>
    </div>
  );
}

function App() {
  const [refreshKey, setRefreshKey] = useState(0);

  return (
    <div className="app" key={refreshKey}>
      <h1>Space Data Center</h1>
      <button className="refresh-btn" onClick={() => setRefreshKey(k => k + 1)}>
        Refresh all data
      </button>
      <div className="data-grid">
        <PlanetsList />
        <MissionsList />
        <AstronautsList />
      </div>
    </div>
  );
}

export default App;

Docs entries used in this lesson

Spotted a mistake in this lesson?

Check yourself

Answer the questions from this lesson. Pick an answer to see right away whether it is correct.

  1. 1. What is the main difference between useEffect(() => {}, []) and componentDidMount?

  2. 2. What happens when we do NOT pass a dependency array to useEffect (no second argument)?

These are 2 of 3 questions for this lesson. Solve the rest in the game.

Hands-on tasks in the game

  • Code editor

    States: [data, setData], [loading, setLoading], [error, setError]. useEffect: setLoading(true), fetch('/api/satellite'), setData(result), setLoading(false). Try/catch for errors. Display: loading ? 'Loading...' : data!

  • Horizontal ordering

    Arrange the correct useEffect syntax with a dependency array:

  • Code editor

    WebSocket Communication System

  • Vertical ordering

    Order the React component lifecycle phases:

  • Code editor

    Global Keyboard Shortcuts System

  1. Coding taskPractice: Data Fetching
  2. QuestionuseEffect and Lifecycle
  3. QuestionuseEffect Without Dependency Array
  4. Put in orderuseEffect Syntax with Dependency Array
  5. Coding taskPractice: WebSocket Connection
  6. QuestionConditional Effect Execution
  7. Put in orderComponent Lifecycle Phases
  8. Coding taskPractice: Event Listeners

Useful articles