Working With API in React Application using Axios and Fetch

Working With API in React Application using Axios and Fetch

Working With API in React Application using Axios and Fetch

Introduction

We know that only API can separate the frontend from the backend. This tutorial will show the typical scenario of how to properly call Axios and Fetch with API in react application and how it works.

Before Starting its recommended to you have basic knowledge on ReactJS like create-react-app, functional components,  class components,  JSX, props and state, useState and useEffect hooks, setState, component lifecycle methods, conditional rendering, list, and keys, building simple forms, and of course necessary JavaScript especially ES6 syntaxes.

In this Article

  • Introduction
  • Rest API
  • Axios
  • Fetch API
  • Fetch API in React
  • Axios in React
  • Conclusion
  • Resouces/Further Reading

Rest API

The REST API(Representational State Transfer) is built on REST architecture, and it has six constraints. Initially communicated by Roy Fielding. It’s not a language or platform-specific, but it can communicate and create an interface with any other language or platform.

These six constraints are:

  • Uniform Interface
  • Stateless
  • Cacheable
  • Client-Server
  • Layered System
  • Code on Demand

Here is an example of REST API  https://jsonplaceholder.typicode.com/posts, a fake online REST API for testing and prototyping.

In this tutorial, we would like to work on NewsApi to fetch news and get it into our application. We have to register individually to get the API key. If you haven’t one, just register for one!

NewsAPI Example

You can implement any API you would like to use. Basically, the approaches are the same, so go to newsapi.org and fill out the form for the new API key. Here I work with my previous one, so I log in!
After login, you will get a generated API key from the dashboard.

API KEY

API KEY

Don’t hesitate! feel free use any API key; just follow the rules and regulation provided by API

Axios
Axios is a lightweight, lightning-fast promised-based HTTP client based on HTTP service, similar to Native Fetch API.

CDN

NPM

YARN

Import

Fetch API

Fetch API provides an interface for fetching data. It will look familiar for someone who has previous experience of working on XMLHttpRequest (XHR). But now its more powerful and flexible features are included. Nowadays all most all modern browser has support on, Fetch API.

Fetch API in React
We have to need to make sure is to have create react app install. So the way to do this is to npm install -g for global create-react-app.
And I have previously installed on my system.

Quick Start

Now we can run npm start or yarn start to view my application on localhost:3000. Here is my folder structure for the project.

Folder Structure

We create a new folder called   /components and inside another nested folder for Headlines.js and  SingleHeadines.js  called /NewsHedlines, So make sure everything working fine as we add and changed App.js.

I added a Bootstrap 4.5.2  CDN for CSS only in index .html for some component styling, and remove all unnecessary comments to keep it simple!

index.html

Let’s start and create the first component Headline.js in /components/NewsHeadlines/ directory. First of all, we have to import react and call other components created just after the Headline component. Basically, in Headline components, we function for iterate and render data from our API and leverage the JavaScript map function.

And we know, when we’re iterating through components, we need a unique key to pass through each, and this one will be the URL from the item object that we’ll get here.

Now let’s export default Headlines!

Headline.js

App.js

We create a stateless component for passing prop and returning some elements here. Basically, we iterate through the title. Now we haven’t any data, and it will not be going to working until passing some data through it. And therefore, the map function will not be working because items are undefined! Finally, we have to export default SingleHeadlines !

SingleHeadlines.js

Now I open pre-installed Postman for handling API requests from News API. From get request, we populate data from Postman like this screenshot and example also mentioned earlier this tutorial.

Postman for API Developemnt

Postman for API Developemnt

The first thing we’re going to create a state inside that component. To create a state, you must be familiar with this if you’ve made a couple of applications with React, so, constructor and we’re initializing the constructor with props, like so. And then we’re going to initialize our state, so this.state. And initialize it with news and create an array, like so.

Okay, so we’re good to go here. And then we’re going to use one of the lifecycle methods called componentDidMount, like so. What we’ll do inside of that function, and as you remember, this got a function that runs after the component has been rendered, and we want to do that to make sure that we can leverage the SingleHeadlines here, like so. So, we’ll create a variable called apiUrl, and we’ll paste the address that we just copied from News API.

Okay, excellent. So we got our URL created, now, what do we do with it? So, this is where the fetch function from ES6 is going to come into work, and this is where we’re going to be able to use even promises actually to fetch, and if there’s a response, then do something with this. If there’s no response, then catch the error, and so on. So, fetch, the fetch method actually takes a URL here, so you could copy this URL and put it here, but I created a variable for that purpose, so I’m going to pass that URL here.

And again, we have access to this from the data we get from Postman, so the URL is here. So this one would be an item.url. And then I always want to maintain a UI UX friendly thing where you want to keep the relationship in-between your user and where you bring them and where you brought them from. So basically, we always want to open whatever link to another tab or page.

Axios in React

A little bit update has been made for Headline.js in terms of Axios

I install Axios using npm install –save axios command and import import axios from ‘axios’ on top of the file.

Here is the little bit update has been made for Axios 

And the final file will look like this.

Headline.js

Result

Fetching News From News API

Fetching News From News API

 

Conclusion
This tutorial was a journey of building a news portal, leveraging external APIs in React. With this knowledge, you should undoubtedly and quickly connect to all kinds of APIs with React and use the Axios and fetch methods we’ve explored. You could drive yourself and continue exercising by adding more APIs to build on your information gateway. Some APIs have more specifications, such as connecting with auth0, use unique authentication methods first, et cetera. For example, learning more about JWT, JSON Web Tokens will help you further when using these APIs with more security features.
Thanks very much for reading this article.

Resources and Tools
React Developer Tools
Project Source Code (Github)
Postman (The Collaboration Platform for API Development)
Axios
Fetch

About the author

Stay Informed

It's important to keep up
with industry - subscribe!

Stay Informed

Looks good!
Please enter the correct name.
Please enter the correct email.
Looks good!

Related articles

15.03.2024

JAMstack Architecture with Next.js

The Jamstack architecture, a term coined by Mathias Biilmann, the co-founder of Netlify, encompasses a set of structural practices that rely on ...

Rendering Patterns: Static and Dynamic Rendering in Nextjs

Next.js is popular for its seamless support of static site generation (SSG) and server-side rendering (SSR), which offers developers the flexibility ...

Handling Mutations and Data Fetching Using React Query

Utilizing React Query for data fetching is simple and effective. By removing the complexity of caching, background updates, and error handling, React ...

7 comments

Munnazzah Aslam October 8, 2020 at 11:33 am
0

Helpful and informative article, thank you!

 
Md Abdul Momin October 8, 2020 at 3:21 pm
0

Thanks, Munnazzah Aslam

Muminur Rahman October 8, 2020 at 7:03 pm
0

Good article for the beginners. Thanks for the writing.

 
Md Abdul Momin October 8, 2020 at 7:29 pm
0

Thanks, Muminur Rahman.

 
 
Moin Khan October 8, 2020 at 8:17 pm
0

Nice article

Ariful Haque October 9, 2020 at 6:52 pm
0

Very well put article bro. Keep the good work up 🙂

 
Md Abdul Momin October 10, 2020 at 12:15 pm
0

Thanks, Ariful Haque

Sign in

Forgot password?

Or use a social network account

 

By Signing In \ Signing Up, you agree to our privacy policy

Password recovery

You can also try to

Or use a social network account

 

By Signing In \ Signing Up, you agree to our privacy policy