Fetching Data from API: async/await
bhuma08
Posted on November 7, 2020
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'
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)
};
You now need to call the function:
pokemon();
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>
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();
Finally, the name of the pokemon is displayed on the browser, like this:
Thank you! I hope this post was helpful :)
Posted on November 7, 2020
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.