"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)