We're planting a tree for every job application! Click here to learn more

How to Fetch Data From an API Using React Hooks

Damilola Adedoyin Ezekiel

29 Sep 2021

5 min read

How to Fetch Data From an API Using React Hooks
  • React

Introduction

What is API?

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.

What is React Hooks?

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.

  • useState: this hook handles state changes in React. It gives us an array to work with and this array is made of two values: the state and the setter function, and this setter function is what we use to update our state.
  • useEffect: this hook lets us perform side effects in a function. Side effects are anything that affects something outside of the current function that is being executed.

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.

Prerequisites

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

Getting started

Create a React Project

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.

Fetch API Method

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.

  • The first thing we do is to import React, useState, and useEffect and then create the default function.
import React, { useState, useEffect } from "react";
export default function App() {
   // lines of code in between
}
  • In our default function, we will declare another function and we will mark this function as an asynchronous function by using the async keyword. We can now await the response from the fetch by using await which we will assign to a variable called response(you can call it anything you want).
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.

Screenshot 2021-09-22 at 18.46.12.png

  • In order to convert the object to JSON, we need to call a JSON function on the response, then we use the await keyword again to wait for the response and assign it to a variable called data(you can call it anything you want).
const data = await response.json();
  • We can now call our fetchPost function in a useEffect hook. This hook will take in two parameters: the first one is the function we are passing into it and the second one is the dependency array that allows the hook to render once.
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.

  • In the same fetchPost function, we will create a new state variable and assign it to the useState hook. The posts will be used in our UI while the setPosts will be used to update the state of the data gotten from the API.
//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);
  };
  • In our return statement, we will have a div that contains two element, one is a paragraph that renders the value of the API data to our UI, and a button that generates a random joke every time we click on it. In order to generate a random joke by clicking this button, we need to pass an onClick props and then set it to the fetchPost function.
 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>
  );
}

Using Axios

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

ezgif.com-gif-maker.gif

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.

Conclusion

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!

Did you like this article?

Damilola Adedoyin Ezekiel

Developer Advocate and Technical Writer

See other articles by Damilola

Related jobs

See all

Title

The company

  • Remote

Title

The company

  • Remote

Title

The company

  • Remote

Title

The company

  • Remote

Related articles

JavaScript Functional Style Made Simple

JavaScript Functional Style Made Simple

Daniel Boros

12 Sep 2021

JavaScript Functional Style Made Simple

JavaScript Functional Style Made Simple

Daniel Boros

12 Sep 2021

WorksHub

CareersCompaniesSitemapFunctional WorksBlockchain WorksJavaScript WorksAI WorksGolang WorksJava WorksPython WorksRemote Works
hello@works-hub.com

Ground Floor, Verse Building, 18 Brunswick Place, London, N1 6DZ

108 E 16th Street, New York, NY 10003

Subscribe to our newsletter

Join over 111,000 others and get access to exclusive content, job opportunities and more!

© 2024 WorksHub

Privacy PolicyDeveloped by WorksHub