How to use Fetch API in JS

Hello guys, sorry to disturb you all; I have just learnt about the fetch API in JavaScript. I understand what it does in terms of asynchronous loading, like having new content displayed on a web page without having to reload the page but I don't really know how to use it, like the arguments it take, what we can do etc... Is there a small project that I can do just to make me more comfortable with that please. Also, while digging into the fetch API, I came across the term "axios"; is that a library that is more performant than the fetch API ?
18 Replies
Jochem
Jochem2mo ago
axios is a pretty old library. It's more powerful than just fetch still, probably, but it's almost never necessary
Jochem
Jochem2mo ago
as for a small project, consume an API somewhere. A popular one is to build a pokedex with https://pokeapi.co/
PokéAPI
An open RESTful API for Pokémon data
Jochem
Jochem2mo ago
MDN Web Docs
Using the Fetch API - Web APIs | MDN
The Fetch API provides a JavaScript interface for making HTTP requests and processing the responses.
Faker
FakerOP2mo ago
hmm for now I can stick to fetch or is it worth learning axios ? Yep, I will start on that thanks !!
Jochem
Jochem2mo ago
Stick with fetch
Faker
FakerOP2mo ago
ok, one last question, I saw that pretty everywhere: " to consume an API" what does that mean ?
Jochem
Jochem2mo ago
generally, to use data from an API in a frontend
Faker
FakerOP2mo ago
ok, thanks ! Hmm I just fetch the api then display the data?
MarkBoots
MarkBoots2mo ago
a really simple example
fetch('https://pokeapi.co/api/v2/pokemon/?offset=0&limit=10000')
.then(response => response.json())
.then(data => listPokemons(data.results));

function listPokemons(pokemons){
const ul = document.createElement("ul");
pokemons.forEach(pokemon => {
const li = document.createElement("li");
li.innerText = pokemon.name;
ul.append(li)
})
document.body.append(ul);
}
fetch('https://pokeapi.co/api/v2/pokemon/?offset=0&limit=10000')
.then(response => response.json())
.then(data => listPokemons(data.results));

function listPokemons(pokemons){
const ul = document.createElement("ul");
pokemons.forEach(pokemon => {
const li = document.createElement("li");
li.innerText = pokemon.name;
ul.append(li)
})
document.body.append(ul);
}
there are some other things to take care of though. What if the api is not responding or returns something you didnt expect. you have to do some extra work for that
Faker
FakerOP2mo ago
Hmm I wrote something like that:
const fetchOptions = {
method: 'GET',
headers: {"Content-Type": 'application/json'}
};


async function fetchData() {
console.log('button clicked !');
try {
const response = await fetch('https://pokeapi.co/api/v2/pokemon/pikachu', fetchOptions);
if (!response.ok) {
throw new Error(`Response status: ${response.status}`);
}
const result = await response.json();
console.log(`Success: ${result}`);
}
catch (error) {
console.error(`Error: ${error}`);
}
}

const btn = document.querySelector("#btn");

btn.addEventListener('click', fetchData );
const fetchOptions = {
method: 'GET',
headers: {"Content-Type": 'application/json'}
};


async function fetchData() {
console.log('button clicked !');
try {
const response = await fetch('https://pokeapi.co/api/v2/pokemon/pikachu', fetchOptions);
if (!response.ok) {
throw new Error(`Response status: ${response.status}`);
}
const result = await response.json();
console.log(`Success: ${result}`);
}
catch (error) {
console.error(`Error: ${error}`);
}
}

const btn = document.querySelector("#btn");

btn.addEventListener('click', fetchData );
I haven't finished yet but I'm not getting the expected result, I'm having [object object]
MarkBoots
MarkBoots2mo ago
well, you're making the result a string with the ${result} console.log("Success": result) will work
Faker
FakerOP2mo ago
oh yeah it worked but why I use template literal isn't it the same thing ?
MarkBoots
MarkBoots2mo ago
with that you're trying put an object into a string. you can just console log the object itself
Faker
FakerOP2mo ago
hmmmmm I'm lost here, in my head, result is just a variable, in order to print what the variable contains, I just use template literals but it happens it isn't working :c
MarkBoots
MarkBoots2mo ago
it's not 'just' a variable. it's an object. template literals only work with strings https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals
MDN Web Docs
Template literals (Template strings) - JavaScript | MDN
Template literals are literals delimited with backtick (`) characters, allowing for multi-line strings, string interpolation with embedded expressions, and special constructs called tagged templates.
Faker
FakerOP2mo ago
ohh I see, thanks !
Faker
FakerOP2mo ago
Can you guys give feedback about my pokedex please
Want results from more Discord servers?
Add your server