Back to basics: Data fetching in React
Tags: react, webdev, javascript, writing
Published: 2022-05-25 19:52:12

---
title: Back to basics: Data fetching in React
published: true
description: Going back to the basics of React
tags: #react, #webdev, #javascript, #writing
cover_image: https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ndi82vmrrra0fowplzxn.png
canonical_url: https://blog.juanfgonzalez.me/back-to-basics-data-fetching-in-react
---

Welcome back friend! 
 
In this article we're going to take a look at one of the basics when working with React.


That is, getting data from an external source and using it in our application.


With that being said, let's get on with it!


![Let's get it on](https://media.giphy.com/media/dynzluggitvMJ6P45c/giphy.gif)





## Setting the stage





Suppose that our task is to retrieve data from an external API and display it on a page. We'll be doing that using only React and the inbuilt functionalities of JavaScript. No external libraries needed.


You might be asking why since there are utilities out there that can speed up the process for us.


The reason for that is twofold. First, most of the times we become a little too dependent on abstractions that don't let us see how things work in general. Second, for the purposes of this article we'll use just what vanilla JS provides us.


Also, revisiting the fundamentals is always a good thing to do when we want to deepen our knowledge and have a better grasp of what we _think_ we know.


Now, lets move on to the details.





## Getting the data


We are going to fetch data from an API and present it on a page. The first thing that we need is that API endpoint that we can call. 


What could we use that we haven't used before?

Hmm...

How about we use the Rick and Morty API?


![image of rick and morty](https://media.giphy.com/media/gk3R16JhLP8RUka2nD/giphy.gif)





We'll fetch the data of the characters and that's what we're going to display on the page.


If you [read the documentation](https://rickandmortyapi.com/documentation/) you'll find that the endpoint we're looking for is in this form 






![Api endpoint](https://firebasestorage.googleapis.com/v0/b/thunk-production.appspot.com/o/users%2F7LEUMMKeAtbI1F7AAefxJR1lCoV2%2Fcontent-images%2F623fe3ac-8a33-40f4-bf78-7f12245d7241%2Fimage.png?alt=media&token=7f2b9cb7-75af-44ae-a587-72149808e933)















If we make a GET request there, we'll get an object with some metadata and the data we're expecting of the characters.


Something like this…



![Image of the results](https://cdn.hashnode.com/res/hashnode/image/upload/v1651182345125/ucnfV9eN1.jpg)




So the results array is what we're mainly interested in. That's what we're going to save as our data to be displayed on the page. 


Now, let's create a function from where we're going to be fetching that data. And we'll be using the Fetch API for that (remember no external libraries needed)


We'll now have something like this:

```javascript
function getRickAndMortyData() {
  const apiUrl = `https://rickandmortyapi.com/api/character`;
  
  fetch(apiUrl)
    .then(res => res.json())
    .then(data => {
        console.log(data.results)
    })
    .catch(error => console.error("The error was:" + error))
    
}
```





That works as our base for getting the data from the API. Now, we'll want to take that data and display it on a page. That's were React comes in to help us out.





## Displaying the data


First, we're going to create the markup for the page.


We'll have a header and a section where the data of the characters will be displayed.


Something like this for starters.




```HTML
<header>
  <h1>Rick and Morty characters
</header>
<main>
  <ul>
    <li>Rick</li>
    <li>Morty</li>
    <!-- ...more characters -->
  </ul>
</main>
```









Now, we'll improve our previous function with some React powers. For instance, when the call to the API gets made, we'll save those results in state so we can use them where necessary.





If you've been using React for a while you will remember that we use to have Class components where we set the initial state and then made the API calls on the `componentDidMount` function.





But since the introduction of hooks, we no longer need to use those class components. The `getRickAndMortyData` function can now remain as a regular function. 





The only changes we'll need to do are the introduction of the hooks for setting state and handling API calls. So we'll change it accordingly like so.




```javascript
function getRickAndMortyData() {
  const [info, setInfo] = React.useState({ 
    characters: [] 
  });
  
  const apiUrl = `https://rickandmortyapi.com/api/character`;

  React.useEffect(() => {
    fetch(apiUrl)
      .then(res => res.json())
      .then(data => {
        setInfo({ characters: data.results })
      })
      .catch(error => console.error("The error was:" + error))
  }, []);
  
  return info;
}
```





Next, we'll take the current markup and improve it with the creation of components. One for the header and one for the characters.





First is the `Header` component that can be something like this.




```javascript
function Header() {
  return (
    <header>
      <h1>Rick and Morty characters</h1>
    </header>
  )
}
```





And then is the `Characters` component that will be listing the characters data that we received from the API.




```javascript
function Characters({ characters }) {
  return (
    <ul>
      {characters.map((character) => (
        <li key={character.id}>
          <img src={character.image}            
               alt="character picture" />
          <label>{character.name}</label>
        </li>
      ))}
    </ul>
  )
}
```





With that done, we only need to use them in the markup passing in the correct data that's going to be displayed.





So the `App` component will look like this.




```javascript
function App() {
  const data = getRickAndMortyData();

  return (
    <>
      <Header />
      <main>
        <Characters characters={data.characters} />
      </main>
    </>  
  )
}
```





## Putting it all together


With all those pieces in place, you'll see that the characters now appear as a list with just 20 of them at first.


If you look at the documentation, you'll see that the response from the API already comes paginated. 

In the `info` object that contains the metadata, there's the info of how many pages there are and the links of the next and previous pages (if they exist)


Knowing this, it wouldn't be difficult to implement a "next page" button that will bring the next 20 characters in the list.


Although, that's something you can implement as an extra credit for this particular exercise. We'll not be extending this article further with the implementation of that functionality.





## Wrapping up 

The styling of this exercises is up to you to make it look however you like.

I personally made it very minimalist with these few lines of CSS.


```CSS
body {
  font-family: Arial, sans-serif;
  text-align: center;
}

ul {
  list-style-type: none;
}

li {
  display: flex;
  flex-direction: column;
}

li img {
  height: 130px;
  width: 130px;
  align-self: center;
}

li label {
  margin-bottom: 1rem;
  font-size: 18px;
}
``` 

And here's a codepen with a working version of this app.

{% codepen https://codepen.io/juanfrank77/pen/yLvBeOv %}


There you have it. A simple React app that gets some data from an external API and then displays it on a page. With no other libraries required. Just Vanilla JavaScript.

"Look ma, no libraries!"

![Look ma, no hands](https://media.giphy.com/media/3o85xzhXeG6bY1ZPZ6/giphy.gif)

---

That's it for this article. Thanks a lot for reading. Hope it was informative and clear enough for you.
If you have any questions or suggestions for this. Send them [my way](https://twitter.com/juanfrank77)!

Take care and see you in the next one.

![Goodbye](https://media.giphy.com/media/7DzlajZNY5D0I/giphy.gif)