I'm currently working on a little imdb-like project in React.js using data from the OMDB API. In order to extract data, I'm first compiling a list of imdbIDs, and then calling those endpoints from the API to get more detailed data.
However, when I add the data to an array, the objects appear correctly in console.logs, but the length of the array is still zero. This makes it impossible for me to display that data in React.
For example:
As you can see, the movie details array here is full of objects but has a length of zero.
I'd appreciate any insight on whether I'm actually properly pushing data to the arrays or not, since I don't seem to be able to access the data from the movie detail array in other react components.
Here's the code I'm working with:
const App = () => {
const [movies, setMovies] = useState([])
const [movieData, setMovieData] = useState([])
const [searchValue, setSearchValue] = useState('')
const movieids = []
const moviedetails = []
const getMovieRequest = async (searchValue) => {
const url = `http://www.omdbapi.com/?s=${searchValue}&apikey=263d22d8`
const response = await fetch(url)
const responseJson = await response.json()
if (responseJson.Search) {
setMovies(responseJson.Search)
}
};
const generateMovieIds = ()=>{
movies.forEach(element => {
const currentid = element.imdbID
movieids.push(currentid)
});
}
const getMovieDetails = async (idValue) => {
const url = `http://www.omdbapi.com/?i=${idValue}&apikey=263d22d8`
const response = await fetch(url)
const responseJson = await response.json()
moviedetails.push(responseJson)
};
const generateMovieDetails = async()=>{
for(const element of movieids){
await getMovieDetails(element)
}
}
useEffect(() => {
getMovieRequest(searchValue)
generateMovieIds()
generateMovieDetails()
console.log(movies.length + ' LENGTH OF MOVIES')
console.log(movies)
console.log(moviedetails.length + ' LENGTH OF MOVIEDETAILS')
console.log(moviedetails)
console.log(movieids.length + ' LENGTH OF MOVIEIDS')
console.log(movieids)
}, [searchValue])
return (
<div className='container-fluid movie-app'>
<div className='row d-flex align-items-center mt-4 mb-4'>
<Heading heading='Movies' />
{movies.length}
vs
{moviedetails.length}
<Searchbar searchValue={searchValue} setSearchValue={setSearchValue} />
</div>
<div className='row'>
<Movies moviedetails={moviedetails} />
</div>
</div>
);
};
export default App;