, , , , ,

/

March 29, 2018

ReactJS Tutorial : Fetching Data From APIs

Using fetch with JavaScript to retrieve data from an API is quite similar using with React. In this post, we will discuss through the steps to use fetch to get data from an API using React. We will be going slow enough that, even if this is your first time using an API, or you’re fairly new to react, you’ll hopefully still be able to follow along.

Let’s start with few definitions as follows: –

API

An API is mostly a set of data often in JSON format with specified endpoints. When we approach data from an API, we want to access definite endpoints within that API framework. For instance, if in the scenario we are using today, we are going to be using the random user API. Within this API, it has randomly developed user data, basically like Lorem Ipsum, but for imaginary users. It has data within the API like email addresses, phone numbers, names and pictures for each user. We don’t need all the data, but we’ll use certain endpoints to grab only the data we want.

Fetch

Since all the data we want is stored in an API, the fetch is how we request that data. We’re basically, requesting API to send us data. The server will then react and will send the data. We can also specify how we want the data to be returned. JSON data is often the easiest to use, so if the server returns anything other than JSON format, if that’s what we’ve requested, we may get an error.

Lifecycle Method

In React, there are a few lifecycle methods. Constructor, ComponentWillMount and Render are three of the lifecycle methods we will be using in this exercise.

State

If you’re new to React, State can be confusing. Think of state as water, ice and vapor. It’s the same object, but has different states depending on conditions. Objects in React are the same way. We can change their state basis on how we want to interact with them.

Okay, with that out of the way, let’s get started.

I’ve selected a user-friendly API to work with, which is a great one to use, especially if it’s your first time or two doing this. Before we start, let’s look at what we want to accomplish. I’ve already finished, but it’s nice to see the finished product, so you know what you’re working toward. Below is basically the end result of what we want to accomplish. Specifically, you will notice that there are hundreds of Thumbnail pictures in the background. That’s not one static image. Rather it’s hundreds of dynamically created photos that we are fetching from an API. Okay, so let’s dive in.

image002

React uses components so it’s easy to make a fetch appeal, or pull data from an API, store it in one component, and then import the entire component to the app, or parent component. Dividing it up into components will help keep our code less cluttered when we fetch from multiple sources or have multiple fetches from the same source.

Here’s how I set up the architecture of this app:-

image003

The background component holds all of the user photos that we’ll pull from the fetch. I have created Background of its own component, and then import it into Splash, so that the code remains cleaner and less cluttered. One can go ahead and set up the architecture of their own app before making the API, if it’s easier to work that way.

Let’s take a look at the Random User API to grab data we want.

image004

Before we go too deep into the project, it’s usually a good idea to go to the API and read any documentation available. This will usually give a good idea of how the API is structured and how to access the data. Often, bigger APIs will register one for a key or have specific ways you need to access the data. We can avoid a lot of that hassle with random User API as is open source and easy to use.

I usually like to pull the data up in a program called Postman, once you’ve have looked over the API documentation. Postman is an enormous way to see the data and target the specific data you want.

image005

Here, in postman at the top, I’ve put the API address into the search bar. I’ve set the request to a GET request, since we’re retrieving data. We could also do a POST, PUT or DELETE request, if we needed to. After the API address I’ve added this line, “results=500”. The Thumbnail pictures we pull will fill the entire background, so I’m asking the API to return 500 results.

Imagine we were pulling data from the API, and rather of a background, we were composing a user profile site. We might only want 1 result, or 3, or whatever. You can filter the results many different ways, but for now, this is as complicated as we are getting. If you scroll through the data, you can see there’s quite a lot there. I’ve highlighted the data that we want. We don’t want any text data, only the pictures. And not just a picture. We only need the thumbnails (which are part of the picture objects). Once we realize what we want, and we can see in postman where that data is nested, it’s easier for us to target later.

Okay, now comes the fun part.

image006

Here we are in the background component. As mentioned earlier, to do a fetch in React, we’ll need to use 3 lifecycle methods.

Let’s look at this as a 3-step process :-

Step 1: Constructor Method

Here in this method we only have to worry about two things. We use super to pass any props from the parent to the child component, once we call the constructor method. Then we set the state. I mentioned state earlier. When you set the initial state, you want to set it as empty, or blank. If it’s going to be a string, it would be an empty string. If an array, an empty array, etc. In this scenario, we only have one thing that we need to set the state of, and that’s the pictures. As we want our pictures in an array, we’re setting it now to an empty array. Then, when we use the fetch to retrieve the data, we’ll go in afterwards, and set the new state to the data that we’ve pulled.

Step 2: ComponentWillMount

In React, lifecycle methods including “Did” are called after something happens and methods including “Will” are called before something happens. But here we require to call the method before, and then pull the data, which is why we are using componentWillMount instead of componentDidMount.

Step 2, part A: Fetch:

Doing one fetch means basically done a thousand. For each one the format will be more or less the same, with just minor differences on how you want to map over the data, etc. We are calling the fetch, and if you’ll notice in the web address, I’ve included the “results=500” filter that I pointed out earlier. You can just copy and paste that URL into your fetch once you have targeted the data the way you want in postman. 

Step 2, Part B: Results:

Here we explain how we want the data returned. Since JSON is easy to work with, and that’s how this data is formatted, that’s what we’re expecting here.

Step 2, part C: Map:

In this we’re mapping over the data that we’ve pulled. This is basically the same thing as doing a for loop. However, sometimes the map function just seems to work better. Considering like this mapping, we’ve told the API we want to get 500 user data objects. As we see in postman, that each user data object contains a lot of information we don’t want, like numbers, address, etc. So, we need to map over it first. Then, we can inform the API that we really need these pictures here and discard everything else.”

Step 2, part D: Key and Return data:

There’s two parts to this step. First, We have set the key to “pic.results” and then specify the data object. The Key feature is used by react to assure that dom elements resemble with data objects. We have created an image tag, with a source that’s set to the data we want to pull. Essentially, what’s happening here is we’ve set a key inside the parent container. We’re informing Inside the parent container, here’s an element and whenever all the data is mapped over, we want it to populate this element with that data. Because we want pictures, that’s why we’re using a <img> element. If we were grabbing the user addresses, names, or phone numbers from this api, we could also include an <li> or <P> tag and use dot notation to specify the data we want inside that element.

Step2, Part E: Set State

Now the last part of this lifecycle method, and arguably the most important. We need to set the new state of our pictures empty array. Using ‘this.setState’, we’re basically saying, “Hey React, remember that empty array we defined as ‘pictures’ earlier? Well, now we want to change its state. So, we’re changing it to this array of pictures we pulled from the API. Is that okay with you?” React is usually pretty nice, so I don’t think it will mind.

Step 3: render:

Render is the last lifecycle method. Now we want to use the new state we defined in the componentWillMount lifecycle method. So, we’re setting up a structure here, and then using curly braces to bring in that state “{this.state.pictures}” .

The last task is to import this background component into the main component, Splash JS, which you can see I’ve already done earlier. Now, keep in mind, once you import the background into Splash.JS, yours will look nothing like mine, because I spent hours screwing with CSS, and CSS is a freaking nightmare, and I’m so done with it. Holy crap! And you thought React was difficult! Good luck with that!

But seriously, if you have any questions or feedback, feel free to reach out. Thanks!