Lambda School: Full Stack – Unit 2, Sprint 5: Components II

Sprint 4

Components II introduces us to methods in which data can be requested from a server. This is a big part of web applications. At work, our clinical EMR made use of technology like this to communicate with pharmacy programs, laboratory programs, financial programs, hospitals and even other EMRs to exchange data. The main point of it was that if data was entered in one program, the user wouldn’t need to re-enter it in another one and risk human error with important clinical and medical information. It also allowed data from one program to power another, so for example, admission data from our program could be used to run financial reports in another one. With hospitals, it allowed key portions of the resident’s health record to travel from our nursing home clients to hospitals so that doctors at the hospitals had access to medical histories and to information that explained why a resident was being hospitalized, and what medical services might need to be provided.

Asynchronous code

Asynchronous code is code that is not sequentially run, from line 1 to the last line in the program (or component). Its code that might need to wait for a response of some sort – especially in the case of code that asks for data to be transmitted back to it from somewhere else on the internet.

Promises

Promises essentially queue up a response for code execution after a request of some sort. With regular, synchronous code, everything executes sequentially. However, if we have a piece of code whose execution is dependent on something, like outside data, then promises can come into play.

The promise allows code to continue on while waiting for data to arrive. Once that data has arrived, the promise executes a callback. A callback can be specified for if the data was successfully retrieved, and a different callback can be specified for if the data request failed.

As per MDN, promises exist in three states:

  • pending: initial state, neither fulfilled nor rejected.
  • fulfilled: meaning that the operation completed successfully.
  • rejected: meaning that the operation failed.

There are two main methods that are used to handle a promise: then and catch. If a request is successful, the “then” callback is run. If it fails, the “catch” callback is run. On a basic level, that’s all there is to it.

As per the Lambda text:

If the promise succeeds, it will return the value as a parameter into a callback passed into .then(). If the promise fails, the callback passed into the .catch() runs, taking an error as its argument.

If a promise gets a successful response, multiple then methods can also be run. This is called chaining promises. It basically looks like this:

const iNeedThisDone =
  (new Promise(runThisAndGetAResponse))
  .then(doThisIfSuccessful)
  .then(doThisIfSuccessfulToo)
  .then(andDoThisAsWell)
  .catch(nowWeHaveToWorkOnTheWeekend);

So, if the new promise runs and is successful, it then runs three callback functions with the response that it received. If it fails and there’s no response, the catch method is run and someone’s weekend is ruined.

HTTP

HTTP, or HyperText Transfer Protocol, is a set of rules that specify how web browsers and web servers communicate, both on the internet and local networks. At work, I had to know a little about HTTP and some other protocols – especially those related to email (SMTP, POP3, IMAP) and I’ve read a little about FTP, or File Transfer Protocol, which is a set of rules about doing exactly what the name says.

Nowadays, when browsing the internet, we actually see HTTPS about as often as HTTP. Its a secure version of HTTP that helps to anonymize and protect data as it travels from one computer through a network to another.

Developers, apparently, need to understand what HTTP methods are, particularly those related to CRUD operations – these are operations that Create, Read, Update and Delete data from other computers, generally servers. There are specific HTTP status codes associated with these operations. Almost everyone online has run into a 404 error, for example, when a web page won’t load.

As per the Lambda text:

HTTP Methods provide a common language or nomenclature that the client can use to let the server know what operation it wants to perform.

When a client needs to ask a server for information it should do a GET request specifying a URL that points to the desired resource.

A POST request is used to ask the server to add or create new resources.

The method used by the client to ask the server to make changes to specific resources is PUT.

To remove or delete data from the server the client needs to send a DELETE request.

HTTP Status Codes are used to indicate if a request has been successful or not and why. The server will set the status code for all responses sent to the client.

axios

axios (its all lowercase) is a JavaScript library that’s used to send HTTP requests to servers. Its easy to use, and under the hood it uses promises, because all server requests are asynchronous. To date, all of the projects that I’ve done that need data from an external API have used axios to get that data, except for one from a YouTube tutorial that used async/await.

axios isn’t necessary to use for data transfer, but its syntax is relatively simple, so its a very popular library. The little experience I had with async/await was also pleasant. It was a fairly simple format to use as well.

I’ve also only really used the .get method in axios, which is apparently an implementation of the HTTP GET request, or the “R” in CRUD (Read). It sends out a request to a server or API asking for data.

To use axios, we need to install it. The Lambda text says to include the following in the head section of our HTML file, which basically downloads axios and lets us use it in the associated JavaScript file:

<script src="https://unpkg.com/axios/dist/axios.min.js"></script>

With the exception of two projects, I don’t remember doing this, however. When I checked even my earlier projects using axios, it looks like I installed it (per project, not just once) in the console (Git BASH) with the following command:

npm install axios

Using Yarn, its done like this:

yarn add axios

In my projects, then I imported it like any other JavaScript library by adding this line at the top of the given component:

import axios from 'axios';

With axios installed and imported, we can use it to request data from an API. Generally, I’ve done that when an application loads, or when a component that needed external data loads. axios calls can be linked to other things though, like clicking a button or other user interactions.

axios takes a string as its first argument. This is the URL of the resource we’re requesting. It then returns a promise to us, which means that its getting the data. As with all promises, .get and .catch deal with the results of the request.

axios.get('http://serverlocation.com/data')
    .then( response => {
        // deal with the response data in here
    })
    .catch( err => {
        // deal with the error in here
    })

Get data and create dynamic components

With the knowledge gained from this unit (the DOM lessons and Components lessons) we now have access to everything we need to connect to an external source, get data from it and iterate over that data to render dynamic components.

Using JavaScript, the steps we need to take to do this are:

  1. Build a component function
  2. Request dynamic data from a server
  3. Build components based on that data
  4. Add those components to the DOM

Its important to remember that data that we receive from an outside server will follow its own format. This will be different for every server. Its a good idea to read the documentation for the server we’re connecting to, or to look at the data itself and learn its format before we try to use it. I generally get arrays of objects, and some of those objects have nested arrays in them, or even other objects. Its also important to identify a unique piece of data that can be used as a key, to distinguish each item in the data from the rest. Sometimes, we’re given an index that we can use for this. Other times, we have to improvise, make use of what’s available and hope for the best.

The following is a project we worked on at Lambda. We had to connect to the GitHub API and get a list of our followers. We then had to iterate over the list and render a card with data for each follower:

github-usercard

I’m somewhat curious now about refactoring the project using React. Maybe I’ll do it at some point, but the React bootcamp from Brad Traversy also uses the GitHub API, so completing that might satisfy my urge.

One thought on “Lambda School: Full Stack – Unit 2, Sprint 5: Components II

Leave a comment