I have a problem when fetch data from TMDB API, I test the API in Postman it works well, but not in my React App. Here is my code (Index.jsx and Movie.jsx). Actually, I can fethc the data in React app in first time, but after a few changes in the
<Movie data={movies[0]} />
to test the movie information. I can no longer fetch the data anymore and I do not know why?
Index.jsx.
import PaginateIndicator from "./PaginateIndicator";
import Movie from "./Movie";
import { useEffect, useState } from "react";
const FeatureMovies = () => {
const [movies, setMovies] = useState([]);
console.log("Rendering")
useEffect(() => {
fetch("https://api.themoviedb.org/3/movie/popular", {
method: "GET",
headers: {
accept: "application/json",
Authorization:
"Bearer MY_TOKEN",
},
}).then(async (res) => {
const data = await res.json();
console.log("Fetched Data:", data); // Debug the response
if (data.results) {
setMovies(data.results);
} else {
console.error("Invalid API response structure:", data);
}
});
}, []); // The second parameter is a dependency array, if any data in this array change, then the callback function (first parameter) will be executed. This will avoid infinite loop
return (
<div className="relative text-white">
<Movie data={movies[0]} />
<PaginateIndicator />
</div>
);
};
export default FeatureMovies;
Movie.jsx.
import { faPlay } from "@fortawesome/free-solid-svg-icons";
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
const Movie = (props) => {
console.log(props);
const {
data: { backdrop_path, title, release_date, overview },
} = props;
return (
<div>
<img
src={`https://image.tmdb.org/t/p/original/${backdrop_path}`}
alt=""
className="aspect-video brightness-50"
/>
<div className="absolute bottom-[10%] left-8 w-1/2 sm:w-1/3">
<p className="mb-2 font-bold sm:text-[2vw]">{title}</p>
<div>
<p className="mb-1 inline-block border border-gray-400 p-1 text-gray-400">
PG13
</p>
<p className="mt-2 text-[1.2vw]">{release_date}</p>
</div>
<div>
<div className="mt-4 hidden text-[1.2vw] sm:block">
<p className="mb-2 font-bold">Overview</p>
<p>{overview}</p>
</div>
<div className="mt-6">
<button className="text-10 mr-3 rounded bg-white px-4 py-2 text-black lg:text-lg">
<FontAwesomeIcon icon={faPlay} />
Trailer
</button>
<button className="text-10 rounded bg-slate-300/35 px-4 py-2 text-black/50 lg:text-lg">
View Detail
</button>
</div>
</div>
</div>
</div>
);
};
export default Movie;
Kan du inte hitta en film eller tv-serie? Logga in för att skapa den.
Vill du betygsätta denna artikel eller lägga till den i en lista?
Inte medlem?