Getting started with fetch API
The fetch API provides an interface for fetching resources. It is the an easy and a logical way to fetch resources. Fetch provides an generic definition of Request and Response objects ( and other things involved with network requests ).
The fetch() methods takes on mandatory argument, the path to the resource you want to fetch. It returns a promise that resolves to the Response to that Request. Once a Response is retrieved, there are a number of methods how the data should be handled.
Example: I'll demonstrate a basic fetch request using a dummy API from JSON placeholder . This dummy API fetches a list of users with associated data.
Have a look at the following code ๐
fetch('https://jsonplaceholder.typicode.com/users')
.then(response => response.json())
.then(data => console.log(data));
This will console log the data in this manner ๐
{
"id": 1,
"name": "Leanne Graham",
"username": "Bret",
"email": "Sincere@april.biz",
"address": {
"street": "Kulas Light",
"suite": "Apt. 556",
"city": "Gwenborough",
"zipcode": "92998-3874",
"geo": {
"lat": "-37.3159",
"lng": "81.1496"
}
},
"phone": "1-770-736-8031 x56442",
"website": "hildegard.org",
"company": {
"name": "Romaguera-Crona",
"catchPhrase": "Multi-layered client-server neural-net",
"bs": "harness real-time e-markets"
}
}
...more user data
Here we are fetching a JSON file across the network and printing it to the console. This is the simplest use case of fetch() which takes only one response โ the path to the resource you want to fetch โ and returns a promise containing the response (a Response object).
Thank You for reading ๐