I'm trying to retrieve the top movies from themoviedb API (https://developers.themoviedb.org/3/movies/get-popular-movies) and I can't seem to render them. I've successfully been able to console.log the data but I can't seem to render them.
I've tried a second useEffect with topThree as the dependency - no luck
import { useEffect, useState } from 'react';
import axios from 'axios';
function Carousel() {
const [movies, setMovies] = useState<any[] | null>(null);
const [topThree, setTopThree] = useState<any[] | null>(null);
const [loading, setLoading] = useState(true);
useEffect(()=>{
const url = `https://api.themoviedb.org/3/movie/popular?api_key=${process.env.MOVIE_API}`;
axios(url).then(({data}) => {
setTopThree(Object.entries(data.results).slice(0,3).map(entry => entry[1]));
}).catch(err => {console.log(err.message);});
}
,[]);
return topThree && (
<>
{topThree.map((movie) => {
<>
<h1>{movie.id}</h1>
<p>{movie.title}</p>
</>;
})
}
<div className="absolute top-[15%] left-[10%]">
</div>
</>
);
}
export default Carousel;
I'm also trying to figure out how to type check the data with TS
interface IData {
id: number,
original_title?: string,
title?: string,
poster_path?: string | null,
backdrop_path?: string | null,
genre_ids?: number[]
}
Any help greatly appreciated as I've been stuck on this. :)
CodePudding user response:
If you have your data, the problem comes from here :
{topThree.map((movie) => {
<>
<h1>{movie.id}</h1>
<p>{movie.title}</p>
</>;
})
}
You should replace by :
{topThree.map((movie) => (
<React.Fragment key={movie.id}>
<h1>{movie.id}</h1>
<p>{movie.title}</p>
</React.Fragment>
))}
In your code you don't return your html in your map. That's why nothing is appearing.
And when you map through data and want to show it, it is better to add the key
to the first element.
Second thing, with the line :
Object.entries(data.results).slice(0, 3).map((entry) => entry[1])
You can easily replace it by :
data.results.slice(0, 3)
as data.results
is already an array.
CodePudding user response:
First thing is that environment variable name always starts with REACT_APP_* e.g. process.env.REACT_APP_MOVIE_API
Now you don't have'nt described how does api response looks like, cause if you are able to fetch data from an api then there is problem with setting data to your topThree state.
Maybe you want to achieve something with this line but it does not seem to be working.
setTopThree(Object.entries(data.results).slice(0,3).map(entry => entry[1]));
Please show me how your response looks like and i can help you out.