Fetching Data from API: async/await

bhuma08

bhuma08

Posted on November 7, 2020

Fetching Data from API: async/await

In my previous blog, I wrote about fetching data from a public API using .then method. I'll now be using async/await method to fetch data.

I'll be using a public api, PokeAPI, which gives you access to Pokémon data .

To start off, add this in your .js file:

const url ='https://pokeapi.co/api/v2/pokemon/1' 
Enter fullscreen mode Exit fullscreen mode

Next, you need to make an async function:

async function pokemon (){
    const resp = await fetch (url); //Here, you fetch the url
    const data = await resp.json(); //The data is converted to json
    console.log(data)
};
Enter fullscreen mode Exit fullscreen mode

You now need to call the function:

pokemon();
Enter fullscreen mode Exit fullscreen mode

You'll be able to see the data on your browser console, like this:

Now, to display a selected data on the browser, you need to create an id or a class in your .html file.

<h1 id="pokemon"></h1>
Enter fullscreen mode Exit fullscreen mode

You are now able to grab the id and add textContent in the pokemon function in your.js file. In this example, I grabbed the pokemon's name, like this:

async function pokemon (){
    const resp = await fetch (url);
    const data = await resp.json();
    document.getElementById("pokemon").textContent = data.name;
};

info();
Enter fullscreen mode Exit fullscreen mode

Finally, the name of the pokemon is displayed on the browser, like this:

Thank you! I hope this post was helpful :)

💖 💪 🙅 🚩
bhuma08
bhuma08

Posted on November 7, 2020

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related

Fetching Data from API: async/await
javascript Fetching Data from API: async/await

November 7, 2020