Calling an API in React
By Lupercal_13 ||
2023-02-23
Hello, today I wanted to share with you how a piece of this blog functions. The other day I was looking for a new feature to add to the homepage of this blog. As I was sitting at my desk working on the blog, I came up with an idea, "Why not add some inspirational quotes to the main page?". So I set out on my journey to not only find a free API to use but also looking at ways to add the data pulled from the API to the main page.
My hope is that in sharing with you how I achieved this, you will be able to learn something new and be able to easily make calls to any API you wish to and add new and exciting features to your own projects!
So if you are ready, lets get started!
Getting Set Up
The first thing that we need to do in order for this to work is make sure that you have everything installed on your work environment that you will need to do this project.
Today I am going to be using Vite (pronounced 'veet') in order to create our React app and get things started. So to get that set up make sure that you have the latest version of NodeJs installed on your machine and open up your command prompt or terminal. You can achieve this on a Windows machine by pressing the windows key + r and type in 'cmd' where prompted.
Inside your terminal type the command npm create vite@latest and follow the prompts to create your new Vite project.
Once you have created the new project, you should run the following:
cd my-project
code .
Now we have successfully created our new project and we can move on to the next steps!
Downloading the necessary dependencies
Now that we have our app up and running we will need to install a couple of dependencies to allow us to customize the look and feel of our application. In this tutorial we are going to be using Tailwind CSS as well as React-icons, so let's get those installed now.
Inside your VS code editor you can press ctrl + ` to open up the terminal. Alternatively, you can use the terminal on your machine that you were previously using to create your app. Just make sure that you are in the correct file location before installing the packages.
Once you have your terminal open and are in the correct folder we are ready to start installing our packages.
Let's start with installing react-icons. In your terminal type the following:
npm install react-icons
Wait for the package to install and then we are ready to move on to installing Tailwind CSS. Once again inside your terminal you will need to type the following:
npm install -D tailwindcss postcss autoprefixer
npx tailwindcss init -pThe first command will install all the necessary files for us to use TailwindCSS inside of our project. The second command with initialize TailwindCSS in our project and create a tailwind.config file for us.
Now we will need to open up our VS code editor and navigate to the newly created tailwind.config file and copy replace the code there with the following:
/** @type {import('tailwindcss').Config} */
module.exports = {
content: [
"./index.html",
"./src/**/*.{js,ts,jsx,tsx}",
],
theme: {
extend: {},
},
plugins: [],
}Great! We are almost set up and ready to get to writing our program. The last thing we need to do to ensure that tailwind is working in our project is navigate to our index.css file and delete everything in the file and replace it with the following:
@tailwind base;
@tailwind components;
@tailwind utilities;Now that our TailwindCSS is set up and ready to go, we have just a couple of other things to do before we can start our development server and get to work.
We will need to find our way to the App.jsx file and get rid of all the unnecessary code from the file. For the purpose of this tutorial you can just delete everything in the file and replace it with the following:
function App() {
return (
<div className="App">
<h1>Hello World!</h1>
</div>
)
}
export default AppI have added an <h1> to the file so that we can see something in our DOM to make sure that everything is working correctly.
Ok, just one more set to go! Next all we need to do is head over to our file explorer on the side panel and go ahead and delete the App.css file, we will not be using it for this tutorial.
That's it! Now we are ready to start our development server and start writing our program. Open up your terminal and type in:
npm run dev
to start up our server. If everything installed correctly you shouldn't see any errors.
Getting our API
Now that we have our project ready to go let's take a look at the api that we are going to be using for this project. Today we are going to be using a free API that will supply us with thousands of inspriational quotes and their authors returned in JSON format. To access the api we will need to use the following endpoint:
https://type.fit/api/quotesNext, we will want to create a variable within our app so that we can access this url whenever we want to make a call to the API. To do that we will add the following code to our App.jsx file:
const apiURL = 'https://type.fit/api/quotes'
With our url now saved into a variable we can easily access it whenever we need to without having to type out the entire url again.
Now that we have our url ready to go we will need to import a few things before we can go any further. We will need to import the useState and useEffect hooks from react as well as some of our icons from react-icons.
Our code should now look like this:
import { useState, useEffect } from "react"
import { FaQuoteLeft, FaQuoteRight } from "react-icons/fa";
import { AiOutlineRedo } from "react-icons/ai";
function App() {
const apiURL = 'https://type.fit/api/quotes'
return (
<div className="App">
<h1>Hello World!</h1>
</div>
)
}
export default AppOnce we have the correct things imported to our app we need to create our function in order to call the API and get the data. So let's do that now.
The first thing we need to do is create a couple of states within our application. We will do this by using the React useState hook. We will create a state for our quote text and one for the author name and set the current state to an empty string.
const [quote, setQuote] = useState("");
const [author, setAuthor] = useState("");Next, below our apiUrl variable and still about the return statement we will create a new async / await function to call the API by using the following code.
const fetchData = async () => {
try {
const response = await fetch(apiURL);
const json = await response.json();
const randomNumber = Math.floor(Math.random() * json.length);
setQuote(json[randomNumber].text);
setAuthor(json[randomNumber].author);
} catch (error) {
console.log("error", TypeError);
}
};Lets break down what exactly is going on above.
- First we created a new asynchronus arrow function called fetchData
- Inside the function we used a try...catch statement in order to do various things within fetchData.
- Inside of our try statement we created a variable called response which fetches the information from our API
- Then we stored that data into a nother variable called json which makes sure that all of our data is converted into a format that our program can access and use
- Next we created a variable called randomNumber which generates a random whole number using the Javascript built in functions Math.floor and Math.random
- Now set our quote state to take in the information from the API and set the state equal to a random quote from our data.
- Then we set our author state to take in the information from the API and set the state equal to the author from our random quote.
- We are now done with our try statement and need to set up our catch statement to catch any errors that may come in and print them out to the console.
After we have set up our fetchData function all we need to do is make sure that it is called each time the page loads. We can achieve this by using the useEffect hook. Inside our useEffect hook we will tell it to call the function fetchData only once when the app loads. The code should look like this:
useEffect(() => {
fetchData();
}, []);For now to make sure that everything is running correctly, let's log the text of the quote and the author to our console.
useEffect(() => {
fetchData();
console.log({qote}, {author});
}, []);If you look in your console you should see both the quote and the author logged out. If everything is good we can go ahead and remove the console.log() from our useEffect hook.
Thats all! We have now successfully called our API and received the data we want from it to be able to use within our app! Congratulations!
Next, let's figure out how we can display the information on our DOM so the enduser is able to see the quote and author.
Displaying Our Data in the DOM
Inside of our return function where all of our JSX is, we can go ahead and remove the <h1> that we added earlier so we are left with a blank canvas, which should look like this:
return (
<div className="App">
</div>
);with that done lets just go ahead and display our information on the DOM in the simplest way possible. To achieve this we are going to create a new <h1> and inside it we are going to dynamically call our quote. Just below it let's create a <p> and add in our author as well.
<h1>{quote}</h1>
<p>{author}</p>We should now see our quote and author displayed on our screen. It isn't pretty yet, but our goal has been achieved and we were able to make a call to the API, get and store the data, and display it on our screen!
The next and final step we need to take before we can say we are finished with our application is to give it some styling so that it is prettier for our user to look at. Let's do that now.
Styling Our Application
Remember at the very beginning when we went through all those steps to install TailwindCSS and react-icons into our application? Well, now it is finally time to put them to use.
We have already imported the necessary icons needed, so no need to worry about that anymore.
To use our icons all we need to do is insert them into our JSX at the bottom of our file. For now our application's JSX should look something like this:
return (
<div>
<FaQuoteLeft />
<h1>{quote}</h1>
<FaQuoteRight/>
<p> - {author}</p>
<AiOutlineRedo/>
</div>
)Don't worry, the app isn't going to be pretty just yet. But this is all the building blocks we will need to use before we can start styling.
Since this post is not about CSS or how to style I am just going to post the final code and you can copy/paste it into your editor. Please feel free the change it up however you like and make it your own!
return (
<div className="w-full flex justify-center ">
<div className="flex flex-col justify-center items-center border w-[80%] px-4 py-8 mt-8 bg-gradient-to-br from-blue-500/40 to-pink-500/40 rounded-xl shadow-lg">
<div className="flex gap-4">
<FaQuoteLeft />
<h1 className="text-lg font-bold tracking-wide">{quote}</h1>
<FaQuoteRight />
</div>
<div className="flex w-full justify-end mr-[50%] mt-4 gap-8">
<p className="text-sm italic font-semibold text-pink-700">
- {author}
</p>
</div>
<div className="flex w-full justify-end mr-8">
<AiOutlineRedo className="fill-gray-500 text-lg cursor-pointer hover:scale-105 hover:fill-gray-600" onClick={fetchData} />
</div>
</div>
</div>
);* on our AiOutlineRedo icon I have added an onClick function that will call our fetchData function whenever clicked, allowing our users to get a new quote without having to refresh the browser.
Congratulations!
We are now finished with our inspirational quote application! I hope that you enjoyed following along with this quick tutorial and were able to learn something new along the way. Once we have mastered how to use APIs within our react application a whole new world of possibilities opens up to us!
Keep learning. Stay curious.
Below is the full code of the finished project:
import { useState, useEffect } from "react";
import { FaQuoteLeft, FaQuoteRight } from "react-icons/fa";
import { AiOutlineRedo } from "react-icons/ai";
function App() {
const apiURL = "https://type.fit/api/quotes";
const [quote, setQuote] = useState("");
const [author, setAuthor] = useState("");
const fetchData = async () => {
try {
const response = await fetch(apiURL);
const json = await response.json();
const randomNumber = Math.floor(Math.random() * json.length);
setQuote(json[randomNumber].text);
setAuthor(json[randomNumber].author);
} catch (error) {
console.log("error", TypeError);
}
};
useEffect(() => {
fetchData();
console.log({ quote }, { author });
}, []);
return (
<div className="w-full flex justify-center ">
<div className="flex flex-col justify-center items-center border w-[80%] px-4 py-8 mt-8 bg-gradient-to-br from-blue-500/40 to-pink-500/40 rounded-xl shadow-lg">
<div className="flex gap-4">
<FaQuoteLeft />
<h1 className="text-lg font-bold tracking-wide">{quote}</h1>
<FaQuoteRight />
</div>
<div className="flex w-full justify-end mr-[50%] mt-4 gap-8">
<p className="text-sm italic font-semibold text-pink-700">
- {author}
</p>
</div>
<div className="flex w-full justify-end mr-8">
<AiOutlineRedo className="fill-gray-500 text-lg cursor-pointer hover:scale-105 hover:fill-gray-600" onClick={fetchData} />
</div>
</div>
</div>
);
}
export default App;
Live example: https://lucky-alpaca-9f878c.netlify.app