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

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
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:
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 highlevelawait, you have to deal withthen/catchstatements. A working code looks like this:More about promises: