I am trying to fetch data from an api and push it into an array and then map through it and render it on page but when i try to map through array i got nothing. Here is my code:
let dataUrlNoPage = `https://api.themoviedb.org/3/movie/top_rated?api_key=${process.env.REACT_APP_TMDB_KEY}&language=en-US&page=`;
let top100Array = [];
const fetchData = () => {
for (let i = 1; i <= 5; i++) {
fetch(dataUrlNoPage + i)
.then((res) => res.json())
.then((data) => {
console.log(data);
if (!data.errors) {
for (let i = 0; i < data.results.length; i++) {
top100Array.push(data.results[i]);
}
return top100Array;
} else {
setResults([]);
console.log('error');
}
});
}
};
fetchData();
console.log(top100Array);
I can see top100Array in console right here.
const listItems = top100Array.map((movie) => (
<li key={movie.id}>
<TopListCard movie={movie} />
</li>
));
return (
<div className="container">
<div className="row">
<div className="col s12 m6">
<div className="add-content">
<h1>Top 20</h1>
<ul className="results">{listItems}</ul>
{console.log(listItems)}
</div>
</div>
</div>
</div>
);
};
But i get empty page here. Thanks for the help.