JSFiddle - React, Tailwind, and code Playground

by Dan Mathisen

HTML

<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
<div class="contactList">
  <p class="error"></p>
  <ul class="favList"></ul>
</div>

JavaScript

// ES6+ things in ALL CAPS
 
 // CLASSES
 class ContactList {
 
 	// DEFAULT PARAMETERS: fall back to document.body if el isn't provided
 	constructor(el = document.body) {
  	this.el = document.querySelector(el);
    this.apiUrl = 'https://reqres.in/api/users';
  }
  
  init() {
  	this.getUsers()
    	.then(result => {
      	this.renderFavView(result);
      });
  }
  
  getUsers() {
  	// ARROW FUNCTIONS: concise way to write a function
  	return $.ajax(this.apiUrl).fail((e) => {
    	this.handleError(e);
    });
   
  	// The above is the same as this:
    
    // let self = this;
    // $.ajax(this.apiUrl).fail(function(e) {
    // 	self.handleError(e);
    // });
    
    // NOTE: "this" is different when using arrow functions. It's worth learning the differences.
    // Basically with arrrows, 'this' is this in the OUTTER scope, not local/inner scope.
    
    // NOTE 2: without brackets, you can return values immediately. All of these are the same and return [2, 4, 6]
    // [1, 2, 3].map(function(item) { return item * 2 });
    // [1, 2, 3].map(item => { return item * 2 } ); // parenthesis around (item) are optional. Required if more than 1 param.
    // [1, 2, 3].map(item => item * 2);
  }
  
  renderFavView (response) {
    const contacts = response.data;
    
    let listItemHtml = '';
    contacts.forEach(contact => {
    	listItemHtml += `<li>${contact.first_name} ${contact.last_name}</li>`;
    });
    
    this.el.querySelector('.favList').innerHTML = listItemHtml;
    
    
    // ES6+
    //
    //
    
    // Let's start with the original and incrementally add some cool ES6+ stuff...
    
    // Original way
    for (var i = 0; i < response.data.length; i++) {
    	listItemHtml += "<li>" + response.data[i]['first_name'] + "</li>";
    }
    
    // Switch to forEach. It's a little cleaner.
    response.data.forEach(function(contact) {
    	listItemHtml += "<li>" + contact.first_name + "</li>";
    });
    
    // Use ARROW FUNCTIONS
   ...