From eb5987108e36136bc079873499f95567b9051029 Mon Sep 17 00:00:00 2001 From: Alberto Mac Date: Mon, 26 Aug 2024 18:52:46 +0100 Subject: revision, and minor fixes --- app/components/Genre.tsx | 84 ++++++++++++++++++++++++++++++++++-------------- 1 file changed, 60 insertions(+), 24 deletions(-) (limited to 'app/components/Genre.tsx') diff --git a/app/components/Genre.tsx b/app/components/Genre.tsx index 13e7ed2..0e90b84 100644 --- a/app/components/Genre.tsx +++ b/app/components/Genre.tsx @@ -1,24 +1,60 @@ -import { useEffect, useState } from "react" - -const Genres = ({id}) => { - - const [genres, setGenres] = useState() - - useEffect(() => { - fetch(`https://api.themoviedb.org/3/movie/${id}?api_key=8216fbb9997cd81a67471e6cb5a6f2df`).then((res) => res.json()).then((data) => { - setGenres(data?.genres) - }) - }, [id]) - - return ( -
- {genres?.map((genre, index) => { - return ( -
{genre.name}
- ) - })} -
- ) -} - -export default Genres \ No newline at end of file +import { useEffect, useState } from "react"; + +const Genres = ({ id }) => { + const [genres, setGenres] = useState([]); + const [loading, setLoading] = useState(true); + const [notFound, setNotFound] = useState(false); + + useEffect(() => { + if (!id) return; // Prevent API call if id is undefined or null + + const fetchGenres = async () => { + setLoading(true); + setNotFound(false); // Reset the notFound state on each new request + try { + const response = await fetch( + `https://api.themoviedb.org/3/movie/${id}?api_key=8216fbb9997cd81a67471e6cb5a6f2df` + ); + + if (response.status === 404) { + console.log('test'); + setNotFound(true); + return; + } + if (!response.ok) { + // If the response is not okay, just set the notFound flag + setNotFound(true); + return; + } + + const data = await response.json(); + setGenres(data.genres || []); + } catch (err) { + console.error("An error occurred while fetching genres:", err); + } finally { + setLoading(false); + } + }; + + fetchGenres(); + }, [id]); + + if (loading) { + return
Loading genres...
; + } + + if (notFound) { + // Instead of throwing an error, simply render nothing if the movie is not found + return null; + } + + return ( +
+ {genres.map((genre, index) => ( +
{genre.name}
+ ))} +
+ ); +}; + +export default Genres; -- cgit v1.2.3-54-g00ecf