A Simple Way of Making API Calls in ReactJS

A Simple Way of Making API Calls in ReactJS

Source

Web applications often rely on data from remote databases and sources. To access this data, you work with the APIs. API stands for Application Programming Interface, and it allows applications to send requests for retrieving, adding, and controlling data from specific databases. When it comes to ReactJS, there are a few different ways of making API requests.

This guide will explain how to make API calls in ReactJS using Fetch API, Axios library, and Async-await. We will work with the following:

Prerequisites

There are a few things you will need for making API calls in ReactJS:

  • Basic understanding of JavaScript, React, and its components.

  • A text editor (VS Code and Sublime Text are great choices).

  • Node.js and npm installed on your computer.

Approach

We will fetch data from an external API endpoint https://jsonplaceholder.typicode.com/todos to get data like the user ID, title, and completed status.

http://jsonplaceholder.typicode.com/users

Set up your environment

Let's start by setting up a basic React app. For that, you can use the create-react-app to set up an environment for working with React and start making API calls on your browser.

  1. Create React project

    The create-react-app automatically downloads and installs all the NPM dependencies, like react, react-dom, and react-scripts, that you need for making API requests.

     npx create-react-app apis
    
  2. Change the directory to the main folder

    Create a folder, rename it to "APIs," and change the directory to the main folder.

     cd apis
    
  3. Create your project structure

    After installing all dependencies and setting up the needed folders, you should have a project structure. This structure contains the needed resources to write your code and fetch data from our API endpoint. The project structure should look like this:

Methods for Fetching Data From API Endpoints

With all these necessary resources available, you can start making API requests in ReactJS. We'll look at three different ways of making API requests:

Fetch API

The Fetch API is very easy to use and provides a unified interface for making HTTP requests across various browsers. With the Fetch API, you can make GET and POST requests, set headers, send JSON data, and more.

You will use the "fetch()" method to send a request and receive the response data. The request and response data passes through as parameters and returns a "Promise." The syntax for making the fetch request is:

import {useEffect} from "react";

function App() {

  useEffect(() => {
    fetch('https://jsonplaceholder.typicode.com/todos')
    .then(response => response.json())
    .then(json => console.log(json))
    }, []);

  return (
    <div>
        This is how we use FetchAPI to "fetch APIs"
    </div>
  );
}

export default App;

Run the application: Open your terminal and run the application with "npm start"

 npm start

Outcome: Open localhost:300 on your browser to see your data.

Axios Library

The Axios library is a much more powerful way of making API requests in ReactJS. It allows you to add additional features such as interceptors, transforms, and more. Additionally, the Axios library makes it easier to work with API responses, allowing you to send multiple requests at once and process the response data more efficiently.

You will install the Axios library through npm:

npm i axios

After installing your dependencies, use the Axios method as follows:


import {useEffect} from "react";
import axios from "axios"

function App() {

  useEffect(() => {
    axios.get("https://jsonplaceholder.typicode.com/todos")
      .then((response) => console.log(response.data));
    }, []);

  return (
    <div>
       This is how we use Axios to "fetch APIs"
    </div>
  );
}

export default App;

Run the application: Open your terminal and run the application with "npm start."

Outcome: Open localhost:300 on your browser to see your data.

Async-Await

Another powerful way of making API requests in ReactJS is to use the async-await syntax. This allows you to write asynchronous code that will wait for the response data before continuing with the code execution.

Async

With Async, you will write promise-based codes that will be executed in the background while awaiting the response. It operates through the loop function and returns a promise when the response data is available.

Await

Await makes Async a powerful tool, allowing you to pause the code execution until the promise is resolved. This means that the response data must be available before any other code can be executed. Also, you can prevent and handle errors using the await syntax.

The Async-Await syntax includes:

import {useEffect} from "react";
import axios from "axios"

function App() {

  useEffect(() => {
    (async () => {
      try {
        const result = await axios.get(
"https://jsonplaceholder.typicode.com/todos")
        console.log(result.data);
      } catch (error) {
        console.error(error);
      }
    })()
  })

  return (
    <div >
         This is how we use Async-Await to "fetch APIs" 
    </div>
  );
}

export default App;

Run the application: Open your terminal and run the application with "npm start."

Outcome: Open localhost:300 on your browser to see your data.

Conclusion

This article has provided an overview of API requests and how to use them in ReactJS. It explains the prerequisites and resources you need, how to set up your environment, and three different ways to make API calls—using Fetch API, Axios library, and Async-await.

With the right resources and knowledge, making API calls on ReactJS is a straightforward process that can generate powerful results. Therefore, constant practice and experimentation with API requests is the key to mastering this skill. Remember to check more resources and document your code for future reference.