Is there a way to access the genres element

40 Views Asked by At

I am creating a Netflix clone and I used TMDB API to get data but I am facing this problem where when I try to access the data it shows undefined but when I log the JSON promise It shows up like this:

Promise {<pending>}
[[Prototype]]: Promise
[[PromiseState]]: "fulfilled"
[[PromiseResult]]: Object

An Image format of object opened form

This is the code:

let fetchDatas = [] // To store Json Data

const fetchData = async () => {
    let data = await fetch(`${baseURL}?api_key=${API_KEY}`); // baseURL = 'https://api.themoviedb.org/3/genre/movie/list' && API_KEY is private.

    if (data.status === 200) {
        return await data.json();
    }
}

fetchDatas = fetchData();
console.log(fetchDatas);

fetch(`${baseURL}?api_key=${API_KEY}`)
    .then(response => response.json())
    .then(data => {
        fetchDatas = data;
    })

console.log(fetchDatas);

Whenever I use API's this problem occurs. How to solve this?

I need to access the promise JSON data and its elements. i.e.: "fetchDatas['genres'] or fetchDatas.genres something like this or what ever way there is!"

so that I can implement it to my Netflix clone

1

There are 1 best solutions below

0
tjarbo On

The issue that you are faced with, is a result of treating asynchronous code as synchronous. And that is a mistake. Please check out one of the links below to learn more about Promises (especially the ones from web.dev).

The following code, should demonstrate it better:

console.log('First code line')
let result = []

console.log('Before fetch')
fetch(`${baseURL}?api_key=${API_KEY}`)
    .then(response => {
      console.log('Got data, convert to object')
      response.json()
    }).then(data => {
        console('Got json data')
        result = data;
    })

console.log('Before result')
console.log(result);
console.log('Last code line')

You will see that "Before result" and "Last code line" being printed before it even says "Got data, convert to object". As fetch() returns a promise, the code will continue to exec synchronously while the async code (the promise handlers .then(...) will be triggered only when the new data arrived (the promise fulfills or rejects). So a long as you cannot do a highlevel await, you have to deal with then/catch statements. A working code looks like this:

function handleGenre(data) {
  // do with the api response what ever you like, like updating the GUI.
  console.table(data)
}

fetch(`${baseURL}?api_key=${API_KEY}`)
    .then(res => res.json())
    .then(handleGenre)
    .catch(e => console.error(e))

More about promises: