Different ways to fetch data using API in React

Last Update: October 21, 2024

Harshil Patel

Table of Contents

  1. Fetch Method
  2. Async/Await
  3. Axios Library
  4. Custom Hook
  5. Fetching in a Component
  6. React Query Library

What is an API?

API stands for Application Programming Interface. It enables the exchange of information and functionality between different systems, such as between a website and a server or between different software applications.

You can think of an API as being like a restaurant waiter. You don't go inside the kitchen to prepare your meal when you dine at a restaurant. Rather, you inform the waiter of your preferences, and they will take your order to the kitchen team. The kitchen team prepares the food and returns it to the waiter, who then delivers it to your table.

An API functions as a waiter for software applications. It is a set of rules that lets one program ask another for something it needs. It serves as a bridge for software apps to communicate and interact.

How APIs Work in Software?

An API provides a set of rules and protocols that allow applications to request or send data. Here’s a simple example:

  • A weather app requests temperature data from a remote server via an API.
  • The API processes the request and returns the current weather data to the app.

Why are APIs Important?

  • Efficiency: They streamline how data and functionality are accessed between systems.
  • Reusability: Developers can reuse existing APIs to build new features instead of creating everything from scratch.
  • Scalability: APIs enable systems to integrate with other apps and services, expanding functionality.
  • Security: APIs expose only the necessary data and functionality, keeping the rest of the system secure.

What is a Hypertext Transfer Protocol(HTTP) request?

When a web browser or a mobile app sends a message to a server, it's known as an HTTP request. A HTTP request involves asking the server for specific data or an action and getting a response. The server responds by interacting with web pages and services.

Using APIs in software development makes things more flexible and efficient. It also enhances security and enables different software systems to work well together.

Types of HTTP Requests
We use various HTTP request methods, such as get, post, put, and delete, to get and store data in our database. But the most common requests made are the get and post requests.

Let's discuss the meaning of these HTTP request methods

GET: This method retrieves data from a specific endpoint. Think of it as asking for information.
POST: This method sends data to a specific endpoint. For example, you can send a message or submit a form. The information will be added to the database.
PUT: This method is used to update a record or data value at a designated endpoint. You're making changes to existing information.
DELETE: This method erases data from a specific endpoint. It's like discarding unnecessary things.

 

1. Using the Fetch Method

fetch() is a native JavaScript function for making HTTP requests. It returns a Promise, which resolves with the response object.

/* Your code... */

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

 

2. Using Async/Await for Cleaner Code

The async/await syntax helps make asynchronous code easier to read by treating it more like synchronous code.

/* Your code... */
useEffect(() => {
 const fetchData = async () => {
 try {
 const response = await fetch('https://jsonplaceholder.typicode.com/posts');
 const data = await response.json();
 console.log(data);
} catch (error) {
 console.error('Error:', error);
}
};

3. Using Axios for Simplified HTTP Requests

Axios is a popular JavaScript library for making HTTP requests. It simplifies request handling and offers features like interceptors, timeout handling, and cancellation tokens.

/* Your code... */
import axios from 'axios';
import { useEffect } from 'react';
useEffect(() => {
axios.get('https://jsonplaceholder.typicode.com/posts')
.then(response => console.log(response.data))
.catch(error => console.error('Error:', error));
}, []);

4. Using Custom Hooks for Reusability

A custom hook abstracts away the logic of fetching data and makes it reusable across multiple components.

/* Your code... */
import { useState, useEffect } from 'react';
const useFetch = (url) => {
const [data, setData] = useState(null);
const [loading, setLoading] = useState(true);
const [error, setError] = useState(null);
useEffect(() => {
const fetchData = async () => {
try {
const response = await fetch(url);
const result = await response.json();
setData(result);
} catch (err) {
setError(err);
} finally {
setLoading(false);
}
};
 fetchData();
}, [url]);
 return { data, loading, error };
};

5. Fetching Data Directly in a Component with useEffect

Fetching data directly in a component is often done using the useEffect hook, which ensures that the data fetch happens when the component mounts.

/* Your code... */
import { useEffect, useState } from 'react';

const Posts = () => {
const [posts, setPosts] = useState([]);


useEffect(() => {
const fetchPosts = async () => {
const response = await fetch('https://jsonplaceholder.typicode.com/posts');
const data = await response.json();
setPosts(data);
};

 fetchPosts();
}, []);

 return (
         <div>
         {posts.map(post => (
         <div key={post.id}>{post.title}</div>
        ))}
       </div>
       );
};

6. Using React Query for Efficient Data Management

React Query is a data-fetching library that provides powerful tools for managing server-side state, caching, and synchronization.

 

/* Your code... */
import { useQuery } from 'react-query';
import axios from 'axios';

const fetchPosts = async () => {
const { data } = await axios.get('https://jsonplaceholder.typicode.com/posts');
return data;
};

const Posts = () => {
const { data, error, isLoading } = useQuery('posts', fetchPosts);

 if (isLoading) return <p>Loading...</p>;
if (error) return <p>Error fetching posts</p>;


return (
        <div>
        {data.map(post => (
        <div key={post.id}>{post.title}</div>
        ))}
        </div>
       );
};

Summary :

Choosing the Right Data Fetching Method in React

 

Method Best Use Case Pros Cons
Fetch Simple API requests Lightweight and native Error handling can be tricky
Async/Await Sequential or complex requests Cleaner syntax, better error handling Still tied to fetch limitations
Axios Complex projects needing headers/interceptors Automatic JSON parsing, request cancellation Adds a dependency
Custom Hook Reusable fetching logic Cleaner components, reusable logic Slightly more setup
Fetch in Component Small projects with simple logic Easy to implement Reduces reusability
React Query Complex apps with caching needs Automatic caching, background updates Adds library overhead
Harshil Patel

Harshil Patel