JS Arrow Functions and Fetch

...


document.getElementById('button1').addEventListener('click', getText);

document.getElementById('button2').addEventListener('click', getJSON);

document.getElementById('button3').addEventListener('click', getExternal);

function getText(){
  fetch('test.txt') // Fetch returns promisses, gotta use .then
    .then(res => res.text())
    .then(data => {
      console.log(data); // then log the data.
      document.getElementById('output').innerHTML = data;
    })
    .catch(err => // catch to catch errors, then do what we want
      console.log(err));    
};

function getJSON() {
  fetch('posts.json') // Fetch returns promisses, gotta use .then
    .then(res => res.json())
    .then(data => {
      console.log(data); // then log the data.
      let output = '';
      data.forEach(function(post){ // para cada do array, cria a LI e append o post.title
        output += `<li> ${post.title}</li>`;
      }); 
      document.getElementById('output').innerHTML = output; // seta o innerhtml pro content de output;
    })
    .catch(err => console.log(err));    
};

function getExternal() {
  fetch('https://api.github.com/users') // Fetch returns promisses, gotta use .then
  // fetching the users data from github
    .then(function(res){ // what we pass into the promisse function is a var named, in this case, res, from response
      return res.json(); // we want to return the text method that is the prototype of the object (because we are dealing with .txt), the apply a function that receives the data
    })
    .then(function(data) {
      console.log(data); // then log the data.
      let output = '';
      data.forEach(function(user){ // para cada do array, cria a LI e append o user.login
        output += `<li> ${user.gists_url}</li>`;
      }); 
      document.getElementById('output').innerHTML = output; // seta o innerhtml pro content de output;
    })
    .catch(function(){ // catch to catch errors, then do what we want
      console.log(err);
    });    
};

// Arrow functions use lexical this, so you dont have to worry about the scope of the function when using this

...

Leave a Reply

Your email address will not be published. Required fields are marked *