Fetch Data from an API with React

Fetch Data from an API with React

A number of web applications and sites rely on third-party APIs and services for data.

Let's look at how to make an API request to a third party API service. This is an open API. Hence, it requires no authentication.

We will utilize the Game of Thrones API (aptly named the API of Fire and Ice) to fetch and display all the 12 Game of Thrones books alongside individual details of each book.

We will use JavaScript's built-in Fetch API to go grab data from the API. You can use any HTTP library for your project like axios. We're using the Fetch built-in one because we don't need to install a package.

We grab and display data in 3 steps:

  • Create a React state variable to hold data
  • Make the API request and store the data
  • Render the returned data

We need to have a way to store data that we get from the API. We'll use React's useState:

jsx
import { useState } from 'react';

function App() {
  const [books, setBooks] = useState(null);

  return (
    <div>render the data here</div>
  )
}

The default value of books was set to null and the setBooks method is used to update the value of books with the returned data.

To handle making an API request, we enclose the fetching action in a function which is called once we need to make an API request. Create a fetchData function in the App() component and fetch the required data from the API endpoint. Do this with:

jsx
import { useState } from 'react';

function App() {
  const [books, setBooks] = useState(null);

  // we will use async/await to fetch this data
  async function getData() {
    const response = await fetch("https://www.anapioficeandfire.com/api/books");
    const data = await res.json();

    // store the data into our books variable
    setBooks(data) ;
  }

  return (
    <div>render the data here</div>
  )
}

This getData() function won't run until we actually call it. We may want to fetch the data as soon as our component is loaded. To run this as soon as our component is rendered, we can use useEffect().

We'll import useEffect and move the getData() function into the useEffect. We'll also give it a second parameter of a blank array [] so that this effect only runs once.

jsx
// + add the useEffect import
import { useState, useEffect } from 'react';

function App() {
  const [books, setBooks] = useState(null);

  // + adding the use
  useEffect(() => {
    getData();

    // we will use async/await to fetch this data
    async function getData() {
      const response = await fetch("https://www.anapioficeandfire.com/api/books");
      const data = await res.json();

      // store the data into our books variable
      setBooks(data) ;
    }
  }, []); // <- you may need to put the setBooks function in this array

  return (
    <div>render the data here</div>
  )
}

Once you have data, you can render it using JSX.

jsx
// ... omitted for speed

return (
  <div>
    <h1>Game of Thrones Books</h1>

    {/* display books from the API */}
    {books && (
      <div className="books">

        {/* loop over the books */}
        {books.map((book, index) => (
          <div key={index}>
            <h2>{book.name}</h2>
          </div>
        ))}

      </div>
    )}
  </div>
)

We conditionally rendered the JSX if books hold any value and then we mapped over the books with books.map().

Chris Sev

Chris Sev

Chris Sev is the co-founder of Better Dev. Coding better every day. Previously he created Scotch.io which was acquired.

Comments

What did you think of the article? Let us know!
(these comments are powered by GitHub issues and use 0 trackers)