Basic Fetch Usage


Basic Fetch Usage

Notice how a fetch() method is used to make a simple network request:

  fetch("https://jsonplaceholder.typicode.com/todos/1")
      .then(result => {
      return result.json()  
   })
   .then((result => {
      console.log(result);
   //logs Object {completed: false, id: 1, title: "delectus aut autem", userId: 1}
   })
   .catch((err => {
       console.log(err);
  });


Fetch(url)

The fetch() method takes in an URL endpoint and is used to make a network request. The fetch() method returns a Promise that contains a Response object.

Notice how the fetch() method returns a Promise that contains a Response object:

  fetch("https://jsonplaceholder.typicode.com/todos/1") //fetch() method used with an URL endpoint
      .then(result => { //result contains a Response object

  });


Extracting data from a Response object:

A Response object has several methods that are used to extract the fetched data.

Here are the common extraction methods:

  • json() is used to extract a json object
  • text() is used to extract a text string
  • blob() is used to extract a file-like object


Notice how the json() method is used to extract a JSONobject:

  fetch("https://jsonplaceholder.typicode.com/todos/1") 
      .then(result => { 
         return result.json() //returns a promise containing the JSON data extracted from the Response object
      })
      .then(result => {
         console.log(result); //logs Object {completed: false, id: 1, title: "delectus aut autem", userId: 1}
     });


Notice how the text() method is used to extract a text string:

  fetch("https://jsonplaceholder.typicode.com/todos/1") 
      .then(result => { 
         return result.text() //returns a promise containing the text data extracted from the Response object
      })
      .then(result => {
         console.log(result); //logs "{completed: false, id: 1, title: "delectus aut autem", userId: 1}"
     });

results matching ""

    No results matching ""