DEV Community

Cover image for Back to basics: Data fetching in React
Juan F Gonzalez
Juan F Gonzalez

Posted on • Updated on • Originally published at 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

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

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 you'll find that the endpoint we're looking for is in this form

Api endpoint

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

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:

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))

}
Enter fullscreen mode Exit fullscreen mode

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.

<header>
  <h1>Rick and Morty characters
</header>
<main>
  <ul>
    <li>Rick</li>
    <li>Morty</li>
    <!-- ...more characters -->
  </ul>
</main>
Enter fullscreen mode Exit fullscreen mode

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.

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;
}
Enter fullscreen mode Exit fullscreen mode

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.

function Header() {
  return (
    <header>
      <h1>Rick and Morty characters</h1>
    </header>
  )
}
Enter fullscreen mode Exit fullscreen mode

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

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>
  )
}
Enter fullscreen mode Exit fullscreen mode

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.

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

  return (
    <>
      <Header />
      <main>
        <Characters characters={data.characters} />
      </main>
    </>  
  )
}
Enter fullscreen mode Exit fullscreen mode

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.

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;
}
Enter fullscreen mode Exit fullscreen mode

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

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


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!

Take care and see you in the next one.

Goodbye

Top comments (1)

Collapse
 
andrewbaisden profile image
Andrew Baisden

This topic used to be so hard for me but when you understand the fetch api, promises and async await it is trivial 😁