"Fetch!" Nope, we're not teaching your dog new tricks. ๐ We're diving into the nitty-gritty of API calls in JavaScript. So buckle up, because if API calls were Pokemon, Fetch would be your Pikachuโsmall, lovable, and shockingly powerful. โก
1๏ธโฃ Fetch is So Fetch! ๐
Let's kick things off by asking the existential questionโwhat the fetch is Fetch? Sorry, couldn't resist. Fetch is the cool kid in the school of API requests. While XMLHttpRequest sits in the corner listening to '80s music ๐ถ, Fetch is out there making async look easy.
fetch('https://dog.ceo/api/breeds/image/random')
.then(response => response.json())
.then(data => console.log(data.message));
// Output: A random dog image URL
2๏ธโฃ Get it Right with GET ๐ฏ
By default, Fetch does a GET request. It gets data like my Aunt Gertrude gets catsโquickly and a lot of them. Here's how to fetch like you've never fetched before.
fetch('https://jsonplaceholder.typicode.com/posts/1')
.then(response => response.json())
.then(data => console.log(data));
// Output: JSON data of the first post
3๏ธโฃ POSTing Bills or POSTing Data? ๐ซ
Sure, you can GET all day, but what about when you want to send some data out into the wild blue yonder of the interwebs? Thatโs when POST comes to the rescue!
fetch('https://jsonplaceholder.typicode.com/posts', {
method: 'POST',
body: JSON.stringify({ title: 'Foo', body: 'Bar', userId: 1 }),
})
.then(response => response.json())
.then(data => console.log(data));
// Output: The new post's JSON data
4๏ธโฃ Error? I Barely Know Her! ๐ซ
When Fetch goes wrong, it doesnโt really scream and shout. Nope, it'll give you a 404 as calmly as a British butler. You have to catch errors like you're trying to juggle flaming torches.๐ฅ
fetch('https://this.isnotarealwebsite.com')
.catch(error => console.log('Oopsie daisy:', error));
// Output: Oopsie daisy: [error details]
5๏ธโฃ Headers: Not Just for Shampoo ๐งด
In API calls, headers aren't above your eyes; theyโre above your request. They tell the API what's going on, like a tour guide in a museum.
fetch('https://jsonplaceholder.typicode.com/posts', {
headers: { 'Content-Type': 'application/json' },
})
.then(response => response.json())
.then(data => console.log(data));
// Output: All the posts, but like, professionally
6๏ธโฃ Abort! Abort! Cancel That Fetch! ๐จ
So, what if you've sent off a Fetch request, but then you're like, "Eh, never mind"? Fear not, the AbortController
is here, a superhero in the realm of JavaScript. This buddy can stop a Fetch operation faster than you can say "Oops!"
const controller = new AbortController();
const { signal } = controller;
fetch('https://dog.ceo/api/breeds/image/random', { signal })
.catch(err => console.log('Fetch aborted:', err));
controller.abort();
// Output: Fetch aborted: AbortError: The operation was aborted.
7๏ธโฃ Fetching in Parallel: Because Time is Money, Honey! ๐ธ
Why fetch one thing when you can fetch ALL the things? Use Promise.all
to fetch multiple things at once and laugh in the face of latency.
Promise.all([
fetch('https://jsonplaceholder.typicode.com/posts/1'),
fetch('https://jsonplaceholder.typicode.com/posts/2'),
])
.then(responses => Promise.all(responses.map(res => res.json())))
.then(data => console.log(data));
// Output: An array of JSON data for posts 1 and 2
8๏ธโฃ Fetched Data Transformation: From Zero to Hero ๐ช
Once you've got that Fetch response, it's not always perfect for your needs. You might need to do some data transformation to get it into shape. Let's get it from zero to hero!
fetch('https://jsonplaceholder.typicode.com/posts')
.then(response => response.json())
.then(data => {
return data.map(post => {
return {id: post.id, title: post.title.toUpperCase()};
});
})
.then(transformedData => console.log(transformedData));
// Output: An array of posts with all titles in uppercase!
Conclusion ๐
Alright, fam! We've learned how to fetch like thereโs no tomorrow. So, let's all be fetchin' fantastic. Got more tips on API calls or stories about how you 'fetched' something up? Share them in the comments below! ๐คโฌ๏ธ
Top comments (0)