From 2108e342e737f8a6c22976282777e784859ddbef Mon Sep 17 00:00:00 2001 From: Shubham Gautam Date: Thu, 17 Dec 2020 13:09:08 +0530 Subject: [PATCH] API which was earlier implemented using XHR has been replaced by fetch (which is fairly an easy substitute available for XHRs), refractored the code --- app.js | 26 ++++++++------------------ 1 file changed, 8 insertions(+), 18 deletions(-) diff --git a/app.js b/app.js index ffe9d90..33a9c4c 100644 --- a/app.js +++ b/app.js @@ -7,23 +7,13 @@ button.addEventListener('click', function(){ }) function getRandomJoke(){ - const ajax = new XMLHttpRequest; - const url = 'https://api.chucknorris.io/jokes/random' - ajax.open('GET', url, true); - - ajax.onreadystatechange = function(){ - if(this.status === 200 && this.readyState === 4){ - console.log(this.responseText); - let data = JSON.parse(this.responseText); - jokeDIV.innerHTML = `${data.value}` - } else { - this.onerror = onerror(); - } - } - ajax.send(); + fetch('https://api.chucknorris.io/jokes/random') + .then(res => res.json()) + .then(jokeObj => { + jokeDIV.innerHTML = jokeObj.value + }) + .catch(e => { + jokeDIV.textContent = 'There was an error!' + }) } - -function onerror(){ - jokeDIV.textContent = 'There was an error!'; -} \ No newline at end of file