#30Building a Reusable useFetch Hook
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
useFetchcustom hook that:- Accepts a URL as a parameter.
- Returns an object with
data,loading, anderror. - Fetches data from
https://thesimpsonsapi.com/api/episodeswhen the hook is mounted. - Updates
loadinganderrorstates correctly. - Refetches data when the URL changes.
- Avoids updating state if the component using the hook is unmounted.
- Integrate
useFetchin 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-testidattributes — they're required for testing. - Use
https://cdn.thesimpsonsapi.com/500as the base path for episode images. - Make sure your hook correctly handles unmounting to prevent React warnings.
- TypeScript interfaces are provided.
Tests
- renders the app title
- shows error message on fetch failure
- renders fetched episodes
- fetches data successfully
- handles fetch error
- refetches data when the URL changes
- does not update state after unmount
- sets loading true while fetching