Javascript fetch event handler doesn't work

1.9k Views Asked by At

I have a question.

How can I do dispatch fetch's event?

In my code, I added addEventListener, but I don't know why It doesn't work.

html

<button id="btn">Button</button>

Javascript

var btn = document.getElementById('btn');

window.addEventListener('fetch', function (event) {
    console.log("fetch add event listener");
});

btn.addEventListener('click', function (event) {
    fetch('https://httpbin.org/get')
      .then(data => {console.log(data)})
});

Codepen Link

http://codepen.io/cnaa97/pen/JEogrr

Please advise me what to do.

Below is the MDN reference link.

https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch#Response_objects

1

There are 1 best solutions below

1
On

I suggest you to use javascript Promise as it is more flexible and efficient to handle response. Please look at the jsfiddle i have created for you https://jsfiddle.net/8j8uwcy7/

HTML

<button id="btn">Button</button>

JavaScript

var btn = document.getElementById('btn');

function fetch(url) {
  // Return a new promise.
  return new Promise(function(resolve, reject) {
     console.log("fetch add event listener");
    // Do the usual XHR stuff
    var req = new XMLHttpRequest();
    req.open('GET', url);

    req.onload = function() {
      // This is called even on 404 etc
      // so check the status
      if (req.status == 200) {
        // Resolve the promise with the response text3

        resolve(req.response);
      }
      else {
        // Otherwise reject with the status text
        // which will hopefully be a meaningful error
        reject(Error(req.statusText));
      }
    };

    // Handle network errors
    req.onerror = function() {
      reject(Error("Network Error"));
    };

    // Make the request
    req.send();
  });
}

btn.addEventListener('click', function (event) {
   fetch('https://httpbin.org/get').then(function(response) {
     console.log("Success!", response);
     }, function(error) {
       console.error("Failed!", error);
     })   
});

Open the browser console and see the response. You can now extract the necessary data from the API.