How to Handle APIs in React?

Published by Pawan Sargar on

How to Handle APIs in React?

Handling APIs in Reactjs is now much easier and simpler. Also, there are many ways that you can call APIs in React, but today we’ll be seeing the most preferred way.

Similar to JavaScript, React also has its built-in fetch()method to call APIs. But that isn’t the best and also doesn’t have the required features. So, today we’ll be using a third-party NPM package called Axios.

What is Axios?

Axios is an NPM package for handling and managing APIs. It’s the most popular and used package for dealing with APIs in the Node environment.

#1 Setup a React Environment or just use CodeSandBox –

If you’ve already set up a new React app then it’s fine, if you haven’t then you don’t need to just head over to Codesandbox.io and click on a new React app and you’d get a brand new React app in just a second.

#2 Install and Setup Axios –

Head over to the terminal and install Axios,

npm install axios

#or

yarn add axios

After installing Axios, let’s import it,

import React from "react";
import Axios from "axios";

#3 Let’s call our very First API?

If you have some knowledge of HTTP & REST architecture, then you might know that there are various HTTP Variables or request methods like GET, PUT, POST, PATCH, DELETE, etc. Today we’ll see the simplest one, and that is GET method.

Also check out,
3 Basic Features of React for Beginners

What does GET request do?

GETrequest, requests or calls the API to get some data back, it’s usually in JSON format. This data can be used to dynamically generate any component or page, for eg:- Products of an Ecommerce website.

To perform a GETrequest with Axios is much simpler, first create a function getUsers(),

const getUsers = async () => {}

and make sure that it’s an Asynchronous function. When dealing with APIs, usually when performing GETrequest, it’s preferred that it should be called Asynchronously, because getting data from a server takes time. And, if we try to use that data before it’s received, we’ll get an error.

Now, let’s use Axios.get() method, we can pass two parameters, the first is the API link and the second is the config object. It isn’t required in getrequest, it’s mostly used in POST, PUT, PATCHrequest methods.

I am currently using a fake users API from JSON Placeholder.

const getUsers = async () => {
	await Axios.get("https://jsonplaceholder.typicode.com/users");
}

Now, you can store the data of the request in a variable, and console log it to check what you’ve received. But before that, we need to call the getUsersfunction. So we can use useEffecthook, to call it every time our document is rendered.

const getUsers = async () => {
	const users = await Axios.get("https://jsonplaceholder.typicode.com/users");
	console.log(users.data);
};

useEffect(() => {
	getUsers();
}, [])

Usually, all of the data is received in a data array, so you can console log it to get more specific data.

Now, if you check your console, this is something you might get,

Handling APIs in React Tutorial

Now, you can dynamically display the data with the help of the ES6 mapmethod, but before that let’s store the data received in a state.

import React, {usestate, useEffect} from "react";
import Axios from "axios";

const Users = () => {
	const [users, setUsers] = useState([]);

	const getUsers = async () => {	
		const users = await Axios.get("http://www.smartphones.com/all-smartphones");
		console.log(users.data);

		setUsers(users.data)
};

useEffect(() => {
	getUsers();
}, [])
}

return (
	<div>
		{users.map((user, index) => (
			<div key={index} className="smarpthone-card">
				<img src={user.name} />
				<h2>{user.username}</h2>
				<p>{user.email}</p>
				<span>{user.website}</span>
			</div>
		))}
	</div>
)

So here we’ve created a useStatehook, and set the received data to the state. Now, as we have that data we are using the JavaScript Array method map, to map the array onto the component, to dynamically generated smartphone card.

Conclusion –

Today we learned how to call an API in React using Axios. We learn to store the received data in a state using React Hooks and finally used the JavaScript Array method map, to dynamically generate smartphone cards.

I hope this post was helpful, if it was make sure to share so that it would motivate us to create more amazing content on web development.

Pawan Sargar
Follow him
Latest posts by Pawan Sargar (see all)
Spread the love
```html ```

0 Comments

Leave a Reply

Avatar placeholder

Your email address will not be published.