How to Retrieve Values from a Movie API?

Struggling with The Movie Database API integration. Specifically, I'm stuck on retrieving the "keys" variable when calling the function with the Movie's id. I'm still learning JavaScript, so this is proving to be a bit challenging. Any assistance would be greatly appreciated.


        const APIURL = "https://api.themoviedb.org/3/discover/movie?sort_by=popularity.desc&api_key=[MY API KEY HERE]&page-1";
        getMovies(APIURL);

        async function getMovies(url) {
            const resp = await fetch(url);
            const respData = await resp.json();
            showMovies(respData.results);
        }

        async function getTrailer(id) {
            const resp = await fetch(`https://api.themoviedb.org/3/movie/${id}/videos?api_key=[MY API KEY HERE]&language=en-US`);
            const respDataa = await resp.json();
            let results = respDataa.results;
            let keys = results[0].key;
            return keys;
        }

        function showMovies(movies) {
            movies.forEach(movie => {
                const modals = document.createElement('div');
                modals.classList.add('modal');
                modals.innerHTML = `  <a target="_blank" href ="https://www.youtube.com/watch?v=${getTrailer(movie.id)}">Watch Trailer</a>`
            });
        }
    

Answer №1

One important rule to always follow is to never expose your API keys when sharing your code, even if it's on a private repository.

Additionally, if you need to retrieve multiple keys, you can use the map function to extract the keys individually before returning them:

async function fetchKeys(id)
{
     const response = await fetch(`https://api.example.com/keys/${id}?api_key=your-api-key`);
     const data = await response.json();
     let keys = data.keys;
     return keys.map(({ id }) => id);
}

Answer №2

Async functions in JavaScript yield a Promise as their return value.
All you need to do is append return keys at the conclusion of your function.

Subsequently, you can execute:

getTrailer(528085).then(data => {
 // manipulate the data here
})

Error handling is also feasible:

getTrailer(528085)
  .then(data => {
    // manipulate the data here
   })
  .catch(err => {
    /* 
    An error has occurred. Use err.toString() to convert the error into a string
    */
})

If you wish to promptly retrieve the returned data from an async function(or a promise), embed your logic inside an async function, then you can easily execute:

let keys = await getTrailer(528085)

Additionally, here is how to manage errors with async/await:

try {
  let keys = await getTrailer(528085)
}
catch(err){
    /* 
    An error occurred. You can use err.toString() to convert the error into a string
    */
}

By the way, in the words of Desiigner, avoid storing your API keys in the client side. Your API key is exposed to everyone. Utilize a server to transmit the API response to the client instead.

Answer №3

We must patiently await the return (as it is a Promise).

function displayMovies(movies) {
      // ensure the forEach callback is asynchronous
      movies.forEach(async (movie) => {
        console.log(getTrailer(movie.id)) // Promise {<pending>}
    
        const trailer = await getTrailer(movie.id);
        console.log({ trailer });
    
        const modals = document.createElement("div");
        modals.classList.add("modal");
        modals.innerHTML = `  <a target="_blank" href ="https://www.youtube.com/watch?v=${trailer}">Watch Trailer</a>`;
      });
    }

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Get the @html.dropdownlistfor filtered for me

Currently, I am working on a project that requires me to filter the options in my second dropdown list based on the selection made in the first dropdown list. While the concept is clear, implementing it becomes tricky as I lack expertise in jQuery or JavaS ...

Establishing headers in hapi.js

Seeking guidance on setting up custom variables for individual routes in hapi.js. How can I configure these variables to be accessible on 'onPreHandler'? Additionally, looking for a way to include headers right before calling reply.continue. Any ...

### Setting Default String Values for Columns in TypeORM MigrationsDo you want to know how to

I'm working on setting the default value of a column to 'Canada/Eastern' and making it not nullable. This is the current setup for the column: queryRunner.addColumn('users', new TableColumn({ name: 'timezone_name', ...

JavaScript code that displays values that are not equal

Here is a code snippet that checks whether two arrays of objects are equal or not. How can we enhance this code to log which answer is not matching? The structure of the arrays: arrayA represents user answered questions, while arrayB contains correct answ ...

Struggling to make the upvoting feature function properly in the Thinkster MEAN Stack Tutorial

While following the MEAN Stack tutorial on this website, I decided to modify my code to utilize Controller as instead of using $scope as demonstrated in their examples. I am encountering an issue with the upvote functionality. Whenever I click to upvote a ...

Dividing ReactJS into different assemblies

I have a flexible .NET application that utilizes plugins to load controllers, views, and components from different assemblies. I am interested in learning React (completely new to me) and I have a question. Can React split its components into separate as ...

Utilizing jQuery to efficiently chunk JSON data through AJAX calls

Is there a way to efficiently handle the retrieval of large amounts of JSON data through an ajax request? I am looking for a jQuery or JavaScript function that can assist with "chunking" the data. For example, I would like the ability to continuously rece ...

Struggling to send information using Angular $resource?

I've been working on sending data to an API using Angular's $resource. Currently, I can successfully retrieve data from my test server using a GET request or querying. However, I'm having trouble figuring out how to send new data to the serv ...

Tips for showing all percentages on a Google PieChart

I'm currently encountering two issues. How can I ensure that the entire legend is visible below the graph? Sometimes, when the legend is too large, three dots are added at the end. Another problem I am facing involves pie charts. Is there a way to d ...

Unable to view cross domain cookies within the browser's development tools

I am currently working on a web application that has an Angular front end running on http://localhost:4200 and a NodeJs backend running on http://localhost:3000. When a user successfully logs in, a cookie is set from the backend containing a token. However ...

What is the best way to store client-uploaded files on the client-side using Bootstrap forms and Express server code?

Essentially, the user submits a file for upload, which is then saved on the client-side (I believe this is handled by PHP), and the upload form I am utilizing is a Bootstrap HTML form. On the server side, I am writing my code with Express. I'm feeling ...

Using the split and join methods in PHP for Javascript operations

Can you assist me with writing this code in PHP? I've attempted multiple times but I can't seem to get it right. Any help would be greatly appreciated! return s.split(/\r?\n/).join("<br>"); Thank you in advance! ...

Is it possible to apply several 'where' condition in pg-promise?

I am currently using pg-promise in combination with express 4 on node 8.2.0. I am trying to concatenate the where condition. However, I have been unable to find a way to achieve this. Can you please assist me? This is what I am aiming for. let ids = [10 ...

Infinite scroll layout meets Semantic UI visibility for a dynamic user experience

I am attempting to implement an infinite scrolling Masonry layout within the Semantic UI framework, utilizing the pre-existing visibility function. While everything appears to be functioning correctly, I am encountering difficulties with getting Masonry t ...

Enhance your webpage with our jQuery plugin that allows you to easily make Ajax

I am currently working on developing a custom jquery plugin. One of the functions within this plugin requires an ajax-call to be made. However, I want to ensure that the function remains chainable, meaning that the ajax-call should only happen after a re ...

Invoke a controller in Prestashop by utilizing AJAX technology

I am struggling to figure out how to call the method / function in my controller. The controller is named TestController.php, and I also have files named Test.tpl and Test.js. Additionally, I am unsure of what to put in the URL field. My goal is to retrie ...

What is the process for importing a .gltf/.glb model into a Three.js application?

After browsing through several related topics on SO, I'm still unable to find a solution to my current issue. The problem I'm facing is that the .glb model simply refuses to load. My Vue application utilizes webpack (specifically the Quasar frame ...

How to effectively utilize wrapAsync in MeteorJS when working with callbacks in the vzaar API?

Issue to Resolve: My current challenge involves retrieving an uploaded video ID asynchronously from an API in order to incorporate it into my code once the video upload process is completed. Unfortunately, I am encountering issues where the returned value ...

Ways to determine whether one side of a selected div is not obstructed by other divs

I am working with some div elements that are all sized 100x100px: Below is the HTML code for the 3 blocks: <div id="plane"> <div class="tile tile3" block-id="1" style-id="3" style="left:50px; top:50px"></div> <div class="tile t ...

Exploring JSON data for auto-complete suggestions

Upon receiving the object from the source, it looks like this - ["road",[["road",53,"0E"],["roadtrip",53,"1E"],["roadrunner",53,"2E"],["roadster",53,"3E"],["roadside",53,"4E"],["roadrage",53,"5E"],["roadcycling",53,"6E"],["roadsideamerica",53,"7E"]],{"k": ...