JS Master The JavaScript Fetch API

 What  is the Fetch API?

Fetch a promise based JavaScript API for making asynchronous HTTP requests.

Fetch is a simple powerful and flexible way to get or send data from / to a server.

Even if the name implies that you can only "fetch" data you can actually make any type of request: GET,POST.PUT.PATCH,DELETE

Each fetch call returns a promise. This allows you to easily handle the data that you receive and the errors you might get.


Let's take  a look at how it works 


  Basic Example : GET

   Let's say we need to get a list of users from the server:

    fetch('https://json://jsonplaceholder.typicode.com/users')

    .then(response=> response.json())

   .then(data => console.log(data))

  .catch(err => console.log(err))


we call fetch() and give it a request URL as its parameter 

Since we know that fetch will return a promise, we use .then() to access the server's response. The response  object returned on line 2 contains all of the response's data, including headers, status code , status message.


Since we know that we're expecting a JSON response we can call the .json()

method to be able to access the actual data in the chained .then() call


We can also use a .catch() block to handle possible errors thrown by the server.


Possible Respose Types

Not all calls will return JSON responses, so it's useful to be aware that the response object returned by fetch has multiple methods you can use;


 //create a clone of the response

response.clone()

//create a new responses with a different URL

response.redirect()

//returns a promise that resolves with an ArrayBuffer

response.formData()

//returns a promise that resolves with a Blob

response.text()

//returns a promise that resolves with JSON

response.json()




Comments

Blogs