10 React Challenges (Beginner): Fetch and Display from an API
Publikováno: 28.5.2019
A number of web applications and sites rely on third-party APIs and services for data.
In this React challenge, we will learn to make an API r...
A number of web applications and sites rely on third-party APIs and services for data.
In this React challenge, we will learn to make an API request to a third party API service. This is an open API. Hence, it requires no authentication.
For this challenge, you will utilize an open Game of Thrones API to fetch and display all the 12 Game of Thrones books alongside individual details of each book.
- CodePen Final: https://codesandbox.io/s/r094p6ylkq\
- CodePen Starter: https://codesandbox.io/s/vyp663nv77\
The Challenge: Fetch List from API
Data received from APIs are usually in JSON format are parsed to standard JavaScript objects. Lists from APIs, when parsed, is usually an array of objects containing individual data.
The main tasks of this challenge are:
- Fetch data from an API when the "Fetch Data" button is clicked.
- Render details from the data returned.
Starter Code
Fork this base CodeSandbox to get started: https://codesandbox.io/s/4qvy5222n9
In the CodeSandbox, you'll find:
- The API URL to make a GET request.
- Styles in
styles.css
to use. - JSX template provided for each item fetched.
Hint
Explore the use of the Axios to make GET requests to a REST API endpoint. Also, look up the use of the .map()
JavaScript method to render data in an array.
Here's what the final page looks like:
Fork this base CodeSandbox to get started: https://codesandbox.io/s/4qvy5222n9
Solution: Fetch and Display List from API
Todo: Video Here
In this React challenge, we aim to fetch data from a provided open API endpoint.
We will utilize Axios, a JavaScript library for making HTTP requests. Also, data returned is stored in state variables before being utilized by the component.
This challenge is completed in 4 steps:
- Install dependencies.
- Create a state variable to hold data.
- Make a data request.
- Render returned data.
Install Dependencies
Install Axios in the CodeSandbox using the "Add Dependency" button on the left sidebar. Import Axios into the App()
component with:
import axios from 'axios';
Create a state variable to hold API data
While we have installed a tool to make API requests, we need to store returned data in state so the component can use it.
Import the useState
hook into the component with:
import React, { useState } from 'react';
In the App()
component, create a state variable called books
using:
import // ...
function App(){
const [books, setBooks] = . useState(null);
return (
// returned JSX here
)
}
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.
Make API request
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 use Axios to fetch the required data from the API endpoint. Do this with:
import // ...
function App(){
const [books, setBooks] = . useState(null);
const apiURL = "https://www.anapioficeandfire.com/api/books?pageSize=30";
const fetchData = async () => {
const response = await axios.get(apiURL)
setBooks(response.data)
}
return (
// returned JSX here
)
}
Using the above snippet, we created a function fetchData
which makes a get request to fetch the Game of Thrones books. Once the request is completed, we used the setBooks
method to assign the data to books
.
Render Returned Data
We have the function to fetch the data, and we can fetch the data while storing it in state. We will move forward to rendering the book name, author, number of pages, country and release date for each returned book in the array.
In the App()
component's returned JSX, pass the fetchData
function to the Fetch Data button. Use the onClick
event handler to fire the function whenever the button is clicked.
Do this with:
import // ...
function App(){
// component variables go here
const fetchData = async () => {
const response = await axios.get(apiURL)
setBooks(response.data)
}
return (
<div className="App">
<h1>Game of Thrones Books</h1>
<h2>Fetch a list from an API and display it</h2>
{/_ Fetch data from API _/}
<div>
<button className="fetch-button" onClick={fetchData}>
Fetch Data
</button>
</div>
{/_ Display data from API _/}
<div className="books">
// Data from API goes here
</div>
</div>
)
}
With this, once we click the Fetch Data button, the fetchData
function is called to fetch data and save it in state.
Using the provided JSX template for rendering each book, use the .map()
method to iterate through the objects in the fetched array. Do this with:
import // ...
function App() {
// Component variables go here
return (
<div className="App">
<h1>Game of Thrones Books</h1>
<h2>Fetch a list from an API and display it</h2>
{/_ Fetch data from API _/}
<div>
// Button to fetch data
</div>
{/_ Display data from API _/}
<div className="books">
{books &&
books.map((book, index) => {
const cleanedDate = new Date(book.released).toDateString();
const authors = book.authors.join(', ');
return (
<div className="book" key={index}>
<h3>Book {index + 1}</h3>
<h2>{book.name}</h2>
<div className="details">
<p>????: {authors}</p>
<p>????: {book.numberOfPages} pages</p>
<p>????️: {book.country}</p>
<p>⏰: {cleanedDate}</p>
</div>
</div>
);
})}
</div>
</div>
);
}
We conditionally rendered the JSX if books
hold any value. Before the date was rendered, we had to convert it to a human readable date. Also, seeing that data on the authors came in an array, we converted the array data into a string separated by a comma and space.
With these, once the Fetch Data button is clicked, a list of all 12 Game of Thrones books is displayed.
Here's what the final page looks like:
You can find the completed CodeSandbox here: https://codesandbox.io/s/r094p6ylkq
Conclusion
For this challenge, we fetched data from an API and displayed the data received.
Have you got questions, suggestions, and comments? We'd love to see them in the comment section. You can find other challenges here and join the live streams here. Happy keyboard slapping!