#30Building a Reusable useFetch Hook
45min

Overview

In this challenge, you'll create a custom useFetch hook to fetch data from an API. The hook should handle loading state, errors, and allow refetching when the URL changes. You will also integrate it into a React component to display the fetched data.

Requirements

  • Implement a useFetch custom hook that:
    • Accepts a URL as a parameter.
    • Returns an object with data, loading, and error.
    • Fetches data from https://thesimpsonsapi.com/api/episodes when the hook is mounted.
    • Updates loading and error states correctly.
    • Refetches data when the URL changes.
    • Avoids updating state if the component using the hook is unmounted.
  • Integrate useFetch in a React component App to display a list of episodes.
  • Show a loading indicator while fetching.
  • Show an error message if fetching fails.
  • Display fetched episodes with their image, name, season, and synopsis following the existing structure.

Notes

  • Don't delete the existing data-testid attributes — they're required for testing.
  • Use https://cdn.thesimpsonsapi.com/500 as the base path for episode images.
  • Make sure your hook correctly handles unmounting to prevent React warnings.
  • TypeScript interfaces are provided.

Tests

  1. renders the app title
  2. shows error message on fetch failure
  3. renders fetched episodes
  4. fetches data successfully
  5. handles fetch error
  6. refetches data when the URL changes
  7. does not update state after unmount
  8. sets loading true while fetching