Home / Blogs

How to Create API Requests With React & Axios in 2023

React JS
·

October 12, 2023

how-to-create-api-requests-with-react-and-axios

In modern web development, making API requests is an essential part of building dynamic and data-driven applications. React, being one of the most popular JavaScript libraries for building user interfaces, is often combined with Axios, a widely-used HTTP client, to handle API communication efficiently.

In this blog, we will explore how to integrate React with Axios to make API requests and fetch data from external sources.

By the end of this guide, you’ll be equipped with the knowledge to create powerful React applications that interact seamlessly with APIs.

To read more about implementing drag-and-drop file upload in React, refer to our blog How to Implement Drag-and-Drop File Upload in React

Step 1 : Setting Up a React Project

Before we dive into Axios and API requests, let’s set up a basic React project to work with. If you have Node.js installed, you can easily use Create React App to scaffold a new project. Open your terminal and run the following commands:

npx create-react-app react-axios-demo
cd react-axios-demo
npm start

Step 2 : Installing Axios

To use Axios in our React project, we need to install it as a dependency. In your terminal, execute the following command:

npm install axios

Step 3 : Making GET Requests

Importing Axios

    To start using Axios, we first need to import it into our React components. In the component where you want to make API requests, add the following import statement:

    import axios from 'axios';

    Fetching Data from an API

      Let’s assume we want to fetch data from a sample REST API (e.g., JSONPlaceholder). In our example, we will retrieve a list of users. Below is an example of how to make a GET request using Axios:

      import React, { useEffect, useState } from 'react';
      
      const UserList = () => {
        const [users, setUsers] = useState([]);
      
        useEffect(() => {
          axios.get('https://jsonplaceholder.typicode.com/users')
            .then((response) => {
              setUsers(response.data);
            })
            .catch((error) => {
              console.error('Error fetching data:', error);
            });
        }, []);
      
        return (
          <div>
            <h2>User List</h2>
            <ul>
              {users.map((user) => (
                <li key={user.id}>{user.name}</li>
              ))}
            </ul>
          </div>
        );
      };
      
      export default UserList;
      

      In this example, we use React’s useEffect hook to fetch data from the API when the component mounts. The retrieved data is stored in the users state using the setUsers function, and then we render the list of users’ names.

      Step 4 : Error Handling

      When working with APIs, it’s essential to handle errors gracefully. Axios provides a convenient way to handle errors using the .catch() method in our HTTP request. If the API request encounters an error, the catch block will execute:

      // ... (previous code)
      
      useEffect(() => {
        axios.get('https://jsonplaceholder.typicode.com/users')
          .then((response) => {
            setUsers(response.data);
          })
          .catch((error) => {
            console.error('Error fetching data:', error);
            setUsers([]); // Clear the user list in case of an error
          });
      }, []);
      

      In the event of an error, we log the error message and set the users state to an empty array to avoid rendering incorrect or incomplete data.

      Step 5 : Making POST Requests

      Fetching data is not the only use case for Axios; we can also make POST requests to send data to the server. For example, let’s create a simple form to add new users to our list:

      import React, { useState } from 'react';
      
      const AddUserForm = ({ addUser }) => {
        const [name, setName] = useState('');
        const [email, setEmail] = useState('');
      
        const handleSubmit = (e) => {
          e.preventDefault();
          if (name && email) {
            const newUser = {
              name,
              email,
            };
            axios.post('https://jsonplaceholder.typicode.com/users', newUser)
              .then((response) => {
                addUser(response.data);
                setName('');
                setEmail('');
              })
              .catch((error) => {
                console.error('Error adding user:', error);
              });
          }
        };
      
        return (
          <form onSubmit={handleSubmit}>
            <div>
              <label htmlFor="name">Name:</label>
              <input
                type="text"
                id="name"
                value={name}
                onChange={(e) => setName(e.target.value)}
              />
            </div>
            <div>
              <label htmlFor="email">Email:</label>
              <input
                type="email"
                id="email"
                value={email}
                onChange={(e) => setEmail(e.target.value)}
              />
            </div>
            <button type="submit">Add User</button>
          </form>
        );
      };
      
      export default AddUserForm;
      

      In this example, we create a form with name and email input fields. When the form is submitted, we use Axios to make a POST request to add the new user to the server.

      Step 6 : Cleaning Up

      When a component is unmounted, it’s a good practice to cancel any pending Axios requests to avoid potential memory leaks or unnecessary API calls. The Axios request can be canceled using a cleanup function in the useEffect hook:

      useEffect(() => {
        const source = axios.CancelToken.source();
      
        axios.get('https://jsonplaceholder.typicode.com/users', { cancelToken: source.token })
          .then((response) => {
            setUsers(response.data);
          })
          .catch((error) => {
            console.error('Error fetching data:', error);
            setUsers([]);
          });
      
        return () => {
          source.cancel('Request canceled by cleanup.');
        };
      }, []);
      

      By implementing the cleanup function, the Axios request will be canceled when the component unmounts, ensuring that no unnecessary API calls are made.

      As you continue to build your React projects, remember to adhere to best practices, consider security implications when handling sensitive data, and always keep an eye on performance optimization. With a solid understanding of React and Axios, the possibilities are limitless, and you can embark on a journey to create impressive and user-friendly web applications.

      To read more about useState Hook in React refer to our blog What is useState Hook in React & How to Manage State in Functional Components

      Horilla Editorial Team Author

      Horilla Editorial Team is a group of experienced writers and editors who are passionate about HR software. We have a deep understanding of the HR landscape and are committed to providing our readers with the most up-to-date and informative content. We have written extensively on a variety of HR software topics, including applicant tracking systems, performance management software, and payroll software etc. We are always looking for new ways to share our knowledge with the HR community. If you have a question about HR software, please don't hesitate to contact us.