Damilola Adedoyin Ezekiel
29 Sep 2021
•
5 min read
API is the acronym for Application Programming Interface is a connection between computers or between computer programs. It is a type of software interface, offering a service to other pieces of software. It allows two applications to talk to each other.
In simple terms, API is like a messenger that takes request, translates the request and return responses. Each time we use an app like Twitter, Instagram, Spotify, etc. we are using an API.
Hooks are a new addition in React 16.8. They let you use state and other React features without writing a class. We will make use of two React hooks in this article, which are the useState and useEffect hook.
In this article, we will look at how to fetch data from API using React hooks and also how to use the data in our application.
Knowledge of JavaScript and React.js is required to follow through with this post. We will create a simple random joke generator.
We will be using CodeSandbox in this tutorial (you can make use of any other editor) and the Chuck Norris joke API
Create a new CodeSandbox using the React starter by CodeSandBox. You can find the final code for this post here. The created project comes with boilerplate code with the app entry point in src/index.js and the home page in src/App.js. Basic CSS styles are written insrc/styles.css.
There are different ways to fetch data from an API and we will look at two methods in this article which are the Fetch API method with async and await and also using an npm package called axios.
The Fetch API is a tool that is built into most modern browsers on the window object and enables us to make HTTP requests easily using promises. Here, we will not be using promises as there is a better way of making requests which is using async/await. It also provides a global fetch method that provides an easy and logical way to fetch resources asynchronously across the network.
import React, { useState, useEffect } from "react";
export default function App() {
// lines of code in between
}
const fetchPost = async () => {
const response = await fetch(
"https://api.chucknorris.io/jokes/random"
);
If we log out the response we get from the API into the console, we will see something like the image below, which is an object.
const data = await response.json();
useEffect(() => {
fetchPost()
}, []);
And that is how we can fetch data from an API using the fetch API method. Before we can render the data from the API into our UI, we need to take some additional steps.
//setting the state variable
const [posts, setPosts] = useState([]);
const fetchPost = async () => {
const response = await fetch(
"https://api.chucknorris.io/jokes/random"
);
const data = await response.json();
//update the state
setPost(postData);
};
return (
<div className="App">
<p> {posts.value} </p>
<button onClick={fetchPost}> get new joke </button>
</div>
);
Here is what the complete code should look like:
import React, { useState, useEffect } from "react";
export default function App() {
const [posts, setPosts] = useState([]);
const fetchPost = async () => {
const response = await fetch(
"https://api.chucknorris.io/jokes/random"
);
const data = await response.json();
setPosts(data);
};
useEffect(() => {
fetchPost();
}, []);
return (
<div className="App">
<p> {posts.value} </p>
<button onClick={fetchPost}> get new joke </button>
</div>
);
}
Axios is a JavaScript library that is used to perform HTTP requests that work in both Browser and Node.js platforms. It is promise-based, and this lets us write async/await code to perform XHR requests very easily. Using Axios to fetch data from an API has a lot of advantages over the Fetch API.
Axios supports all modern web browsers,
It performs an automatic transformation of JSON data
It allows the canceling of requests and request timeout.
Axios has built-in support for download progress.
In order to use Axios in our application, we have to first install it as it is not built into browsers like the Fetch API.
npm install axios // if you use npm
yarn add axios. // if you use yarn
We can also add these dependencies in CodeSandbox using the “Dependencies” section of the Explorer.
import React, { useState, useEffect } from "react";
import axios from "axios";
import "./styles.css";
export default function App() {
const [posts, setPosts] = useState([]);
const fetchPost = async () => {
const response = await axios("https://api.chucknorris.io/jokes/random")
setPosts(response.data)
}
useEffect(() => {
fetchPost();
}, []);
return (
<div className="App">
<p> {posts.value} <p>
<button onClick={fetchPost}> get new joke😂</button>
</div>
);
}
This is the same code as the Fetch API method. We only changed it to use Axios instead and we can see from the sample, we do not need to convert the response object to JSON as Axios automatically handles that for us.
We can also wrap our code in a try and catch statement so as to handle any error that might come up and this will also make debugging easier.
const fetchPost = async () => {
try{
const response = await axios("https://api.chucknorris.io/jokes/random");
setPosts(response.data);
}catch(err){
console.error(err)
}
};
Here is what the finished product should look like
Since we did not talk about styling, you can make use of the CSS code below to make it look exactly like the demo.
.App {
font-family: sans-serif;
text-align: center;
width: 30rem;
height: auto;
padding: 2rem;
background-color:# 06d1c0;
border-radius: 10px;
margin: 10rem auto;
}
button{
background-color:# b1d8da;
padding: 0.5rem 1rem;
border-radius: 10px;
border: 2px solid# b1d8da;
font-size: 15px
}
You can find the CodeSandbox demo here.
We have explored two methods of fetching data from an API, and as stated before, there are different ways to do this. Let me know which method you have been using or prefer.
Thanks for reading!
Ground Floor, Verse Building, 18 Brunswick Place, London, N1 6DZ
108 E 16th Street, New York, NY 10003
Join over 111,000 others and get access to exclusive content, job opportunities and more!