0

I have a JavaScript script that makes a request to an api through the fetch api and then pushes the json response to a list and I want to access the response object inside the list through it's index but the item returns undefined like it isn't in the list.

I tried this:

let trendingMoviesDetails = []
fetch(`https://api.themoviedb.org/3/movie/529203?api_key=${key}&language=en-US&append_to_response=videos,release_dates`)
.then(response => response.json())
.then(response => {trendingMoviesDetails.push(response)})
console.log(trendingMoviesDetails, trendingMoviesDetails[0])

but why does the console print out trendingMoviesDetails[0] as undefined. This is the result on chrome:

[]0: {adult: false, backdrop_path: '/fmIp40ev4VGquK2bMo52PQgaV2d.jpg', belongs_to_collection: {…}, budget: 65000000, genres: Array(5), …}length: 1[[Prototype]]: Array(0) 
undefined
Timi
  • 3
  • 2
  • You didn't wait for the fetch to complete. `fetch` just starts an async operation, it does not wait for it to finish. So the console.log happens before there is any data. See https://stackoverflow.com/questions/14220321/how-to-return-the-response-from-an-asynchronous-call – James Apr 04 '22 at 13:49
  • For why you get the weird console log of empty array, but expanding it shows the result, see [is-chrome-s-javascript-console-lazy-about-evaluating-objects](https://stackoverflow.com/questions/4057440/is-chrome-s-javascript-console-lazy-about-evaluating-objects) – ASDFGerte Apr 04 '22 at 13:52

1 Answers1

1

This is because fetch is asynchronous. You're pushing some values in the then handler - which means it will be performed after the fetch promise is resolved, while trying to access the [0] value outside that handler.

You may either put all the code that has to be called after said promise is resolved into that handler, or use async/await like this:

async function someFunc() {
 let trendingMoviesDetails = [];
 
 const response = await fetch(`https://api.themoviedb.org/3/movie/529203?api_key=${key}&language=en-US&append_to_response=videos,release_dates`);
 const json = await response.json();
 
 trendingMoviesDetails.push(json);
 console.log(trendingMoviesDetails, trendingMoviesDetails[0])
}
k102
  • 7,861
  • 7
  • 49
  • 69