Back
React
Fri Aug 02 2024

Fetching Data using APIs in React

React has changed the way we develop user experiences, but an excellent UI is meaningless without the data that supports it. In this blog, we'll explore how to request data from APIs in React, which is a fundamental skill for any React developer.

 

What is an API?

API stands for Application Programming Interface. It allows information and functionality to be exchanged between systems, including websites, servers, and software applications.

Let's say you are a student who needs research materials for a study. You go to check the library catalog to see what books and materials are available and how to find them. The library catalog is considered as API documentation in this analogy. After selecting the materials, you request the materials and books from the librarian which is like making an API request. Then the librarian hands you the books and materials which is like getting API responses. You use the materials for your study. Using API is like accessing what you need without creating everything from the scratch.

APIs are widespread in the digital world. An API is retrieving the information of weather from a weather service when we check the weather on our phone. When you book a flight on a travel website, APIs work behind the scenes to compare availability and rates from several airlines. Even logging into a website with your Google or Facebook account is an example of an API in operation.

In the following sections, we'll explore two of the most commonly used methods for fetching data using APIs in React.

 

Using Javascript fetch() method

The fetch() method is well-known for retrieving data from APIs. It is recognized as the simplest and most used approach. fetch() is a built-in JavaScript function that makes network requests. It's like sending a letter and waiting for a reply, but much faster.

Syntax

fetch(url, options)
  .then(response => response.json())
  .then(data => {
    // Handle the data
  })
  .catch(error => {
    // Handle any errors
  });

Let's breakdown the above syntax: 

  1.  fetch(url, options): The url is mandatory which contains the URL of the resource you want to fetch whereas options is an object that lets you control different settings and it is optional.
  2. then(response => response.json()): This converts the response to JSON format. You can use other methods like response.text() for plain text.
  3. then(data => { ... }): This is where you handle the parsed data.
  4. catch(error => { ... }): This catches any errors that occur during the fetch process.

Implementation

import React, { useState, useEffect } from "react";

const App = () => {
  // State to store the list of users and loading status
  const [users, setUsers] = useState([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);

  useEffect(() => {
    // Define the function to fetch data
    const fetchData = async () => {
      try {
        // Place your order (fetch data)
        const response = await fetch(
          "https://jsonplaceholder.typicode.com/users"
        );

        // Check if response is OK
        if (!response.ok) {
          throw new Error("Network response was not ok");
        }

        // Convert response to JSON
        const data = await response.json();

        // Update the state with the fetched data
        setUsers(data);
      } catch (error) {
        // Handle errors
        setError(error.message);
      } finally {
        // Update loading status
        setLoading(false);
      }
    };

    fetchData();
  }, []); // Empty dependency array means this effect runs once when the component mounts

  return (
    <div className="App">
      <h1>User List</h1>
      {loading && <p>Loading...</p>}
      {error && <p>Error: {error}</p>}
      {!loading && !error && (
        <ul>
          {users.map((user) => (
            <li key={user.id}>
              {user.name} - {user.email}
            </li>
          ))}
        </ul>
      )}
    </div>
  );
};

export default App;

The function sends request to https://jsonplaceholder.typicode.com/users, converts the response to JSON and updates the state. After the fetching is complete, it displays a list of users' names and emails.

  

Using Axios library

Axios is a JavaScript library that makes it easier to send HTTP requests. Think of it as a friendly helper that goes out to the internet, grabs the data you need, and brings it back to your app, all while making your code cleaner and easier to manage. It automatically transforms JSON data for you.

To use Axios for data fetching, first you need to install Axios using the following command:

npm install axios or yarn add axios

Syntax

const getData = () => {
  axios
    .get('https://api.example.com/data') // Replace with your API endpoint
    .then(response => console.log(response.data))
    .catch(error => console.log('Error fetching data:', error));
};

// Call the function to fetch data
getData();

Let's break down the above syntax:

  1. axios.get(url) sends an HTTP GET request to the specified URL to retrieve data. You can replace 'https://api.example.com/data' with the actual URL of the API you want to fetch data from.
  2. then(response => ...) is a promise-based way to handle the successful completion of the request.
  3. catch(error => ...) handles any errors that occur during the request.

Implementation

import React, { useState, useEffect } from "react";
import axios from "axios";

const Axios = () => {
  const [data, setData] = useState([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);

  useEffect(() => {
    const fetchData = async () => {
      try {
        const response = await axios.get(
          "https://jsonplaceholder.typicode.com/users"
        );
        setData(response.data);
      } catch (error) {
        setError(error.message);
      } finally {
        setLoading(false);
      }
    };

    fetchData();
  }, []);

  return (
    <div>
      <h1>Only Users' names</h1>
      {loading && <p>Loading...</p>}
      {error && <p>Error: {error}</p>}
      {!loading && !error && (
        <ul>
          {data.map((item) => (
            <li key={item.id}>{item.name}</li>
          ))}
        </ul>
      )}
    </div>
  );
};

export default Axios;

In the above example, the component fetches user data from the JSONPlaceholder API using Axios. You need to add the above component in the App.js for the component to work.

 

Conclusion

This blog discusses the two most frequently used methods of fetching API data in React. These approaches will assist you in developing advanced applications. The fetch() method provides a built-in, basic technique to handle network requests, whereas Axios adds capabilities like automated JSON transformation and improved error handling to ease the code and development process.