Step By Step Tutorial

How to consume APIs In React

A guide to fetching data with React

Hussain Arif
Level Up Coding
Published in
6 min readJul 12, 2020

--

A Man standing on top of a hill
Source: Joshua Earle On Unsplash

One of the most interesting projects a beginner can do while learning a framework is to build a random quote generator. In this tutorial, we’ll be building a web app that will send us an inspirational quote of the day when we run the program. Along the way, we will also learn about the fetch method in ReactJS.

In the end, this will be the result of our program:

Quote Of the day:Every day you have a choice to be honest or deceptive. If you commit to telling the truth, you will win..
Quote Of The Day. This will be our objective

Getting Started

Just like creating any React app, let’s run create-react-app .

npx create-react-app quotes-app

We won’t be installing any other modules. However, we will be using the Quote Of The Day API to fetch our golden words.

They have quotes from several categories including inspire. As the name suggests, this inspire category will give us inspirational sayings. According to their terms of service, we also have to attribute the website.

For attribution, this will be our template as provided by the API website:

<span style="font-weight: bold;">
<img src="https://theysaidso.com/branding/theysaidso.png" />
<a href="https://theysaidso.com" title="Powered by quotes from theysaidso.com" style="color: #ccc;">
They Said So®
</a>
</span>

Let’s now start with our app!

Fetching the Quotes

Defining the FetchQuote function

In your project’s root directory, create a new file called quotesFetcher .

Let’s start by importing react , and the useState, and useEffect functions from react:

In quotesFetcher.js

import React,{useState,useEffect} from "react"

We will use useState to assign several hooks. The values of these hooks will be displayed to the page. useEffect will be the onComponentMount equivalent if we would be using class-based components.

--

--