12 Tweets 19 reads Feb 11, 2022
A complete Introduction to Fetch API.
Thread ๐Ÿงต๐Ÿ‘‡๐Ÿป
Fetch is a web API that provides an interface to fetch resources across the networks.
For making a request, we have the `fetch()` method.
The fetch method is entirely based on `promises` that can be resolved to the request's response.
Before moving further, let's talk a little bit about Promises. ๐Ÿ‘‡๐Ÿป
We can say that Promise is nothing but the object that represents the result of an asynchronous call.
The result can either be successful or failure.
A Promise has three states:
Pending: Neither fulfilled nor rejected.
Resolved: Promise fulfilled.
Rejected: Promise rejected.
There are two possible scenarios when you fetch resources through an API call.
- The server will return the resource: Promise fulfilled.
- The server will throw an error: Promise rejected.
If you want to learn more about Promise, please take a look here.
developer.mozilla.org
Now let's get back to fetch API.
Fetch takes at least one argument, i.e., the path of the resource you are interested in fetching.
Fetch API always returns a promise which will be captured by the `then()` method.
Rejected promises can be captured by the `catch()` method.
In the above code snippet, we didn't mention the HTTP request.
If we don't specify the HTTP method, the fetch API will use GET by default.
What if we want to make POST, PUT, or DELETE requests?
The fetch method takes a second optional argument as well.
This second parameter is nothing but the `init` object.
It is mainly used to pass the HTTP method and request body, but you can pass many other things.
Let's see that in practice. ๐Ÿ‘‡๐Ÿป
With that being said, this is pretty much it for this thread.
Follow @Rapid_API for more exclusive content.

Loading suggestions...