Learn How API Integration with REACT works
Programming

Learn How API Integration with REACT works

In this article, I'm going to show how to integrate an API with React using a project-based approach.

Before we dive right in, let's talk about what an API really is.

 Let's take a look at this scenario: you go to a restaurant, a waiter comes over and you request a specific meal--could be off a menu or from what you usually get from there. He tells you he'll be back. After some minutes, he brings to you from the kitchen what you ordered.


The analogy above perfectly described an API’s relationship with both client and the server. A client (you) request specific data (food) from an API (the waiter) and gets back a response from the server (kitchen).

Application Programming Interface, API, serves as the middleman or server between a client and a server. It takes a request and returns a response. This response is normally in a JSON format, although there are other formats like .txt, .xml but .json is the most common. There are different types of APIs but in this project, I'm going to use a third-party API called Advice slip API. This project is a simple project, so everything will be shown in the App.js file.

 Let's start!

Step 1: Create your React app: npx create-react-app advice-generator

Step 2 : Clean up your app and build your front-end.  You can choose whatever way you want. I'm choosing to just focus on ensuring the functionality of the code. 

Step 3: Advice Slip JSON API as the name implies returns a piece of advice as a response. Let’s check it out. Go to api.adviceslip.com.

Like every other API site, Advice Slip API contains documentation that will help you know how to make a request to its API. Think restaurant menu, it guides you on what to order from the restaurant.


Advice Slip API is free and no API key is required for you to make a request and get a response from its API. The documentation on the landing page shows the various endpoints for you to make requests on. These endpoints are used for: getting random advice, searching for an advice, and getting an advice by its id.
For this project, I want to just generate random advice every time I make a request. So I will be using the endpoint provided: api.adviceslip.com/advice
If you hit the above link in your browser, you’ll get back a slip object. In this object, there is an id and an advice. You’ll notice every time the endpoint, a different advice is returned. This is what we need to proceed with the project. 


Step 4 : In App.js:

 

import {React, useEffect, useState} from "react"
export default function App() {

useEffect(()=>{
getAdvice();
}, [])
const [advice, setAdvice] = useState({})
const [loading, setLoading] = useState(true)
const [errMsg, setErrMsg] = useState('')
const [error, setError] = useState(false)
const getAdvice = async ()=>{
try{
setLoading(true)

const response = await fetch("https://api.adviceslip.com/advice")
const data = await response.json()
setAdvice(data.slip)

setLoading(false)
}catch(err){
setError(true)
setErrMsg(err.message)
}
}

return (
<div className="App">
<h1>Advice Generator</h1>
{
!error?
<div className="advice">
{loading?
<h2>Loading...</h2>
:
<>
<h2>
Advice number {advice.id}
</h2>
<blockquote>"{advice.advice}"</blockquote>
</>
}
</div>
:
<>
<p>{errMsg}. Reload page</p>
</>
}
<div>
<button onClick={getAdvice}>New Advice</button>
</div>
</div>
);
}


There are four pieces of state used in the code: the advice state, the error (err) state, the error message (errMsg) state, and the loading state. I’ll explain as we go along.

The function ‘getAdvice’ is wrapped in a try-catch. This is mostly intended for handling errors due to failure of data to be fetched, in essence, network error. Other than that, there will be barely any errors in this project. 

The useEffect ensures the getAdvice function runs when the component mounts. This is why we see an advice already generated when we visit or reload the page.

In getAdvice:

setLoading(true)

const response = await fetch("https://api.adviceslip.com/advice")
const data = await response.json()
setAdvice(data.slip)

setLoading(false)


Initially, the loading state is set to false because we are not fetching any data until the getAdvice function is called. Once the function is called, the loading is set to true. The time taken to fetch data varies and the loading state is important to show that the data is being fetched.

As soon as the data is fetched, the advice state takes in the slip object fetched and loading is set to false because we don’t have to wait again since we’ve got what we wanted: The advice object. All this happens in the try block.


catch(err){
setError(true)
setErrMsg(err.message)
}


To catch errors, the error state is set to true. This is basically saying, ‘yes, there is an error while fetching data’. If there is no error, this state remains false. The errMsg state stores the error into a state to be used later.


Now that we have our data, we want to display it on our page and generate a new advice each time we click on a button. 

{
!error?
<div className="advice">
{loading?
<h2>Loading...</h2>
:
<>
<h2>
Advice number {advice.id}
</h2>
<blockquote>"{advice.advice}"</blockquote>
</>
}
</div>
:
<>
<p>{errMsg}. Reload page</p>
</>
}


Before we begin to display our data, It’s important to check if there is an error to avoid our app from crashing.

In this conditional, we first check if there is an error. If none, we then check if the data is fetched, if it’s still loading, the content should display “loading… ”. But if it has already loaded (if loading is false), we can use the id and advice of the advice state.

If there is an error, an error message should be displayed letting the user see what was wrong. It’s almost like you ordering something and perhaps the food was dropped midway to being served. The waiter can come back and explain the situation. As the waiter tells the bad news, you actually know what had happened. This is better than being delayed and wondering what went wrong with your order.

<div>
<button onClick={getAdvice}>New Advice</button>
</div>


Back to the code, to generate another advice, we use a button that calls on the getAdvice function and as I explained earlier, this endpoint returns any random advice. So, the advice state is constantly changing with each click, changing its object as the data is fetched over and over again.

And that’s it!

That was easy, wasn't it?


Conclusion

API integration is a very important aspect of programming.  It saves time and effort in creating certain backends from scratch every time. Common ones include Facebook, Google, Youtube, Twitter, etc.  You can use third-party APIs to track locations on your app, for easier login,  for online payment, and the list goes on. As a front-end developer, you can get a glimpse of how back-end and front-end interact.

I hope you've learned a lot more about APIs in this article. Till next time!

  • Hikmah
  • Mar, 27 2022

Add New Comments

Please login in order to make a comment.

Recent Comments

Be the first to start engaging with the bis blog.