Open In App

Different ways to fetch data using API in React

Last Updated : 28 Feb, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

API: API is an abbreviation for Application Programming Interface which is a collection of communication protocols and subroutines used by various programs to communicate between them.

A programmer can make use of various API tools to make its program easier and simpler. Also, an API facilitates programmers with an efficient way to develop their software programs.

Different Ways to Fetch the Data using API in React:

There are 4 different ways to fetch the data using API in react. Below is the stepwise implementation . For the sample data, we have used the API endpoint from

http://jsonplaceholder.typicode.com/users

1. Fetch Data from API using fetch method:

The fetch() method in JavaScript is used to request to the server and load the information in the webpages. The request can be of any APIs that return the data of the format JSON or XML. This method returns a promise.

Javascript




// Filename - App.js
 
import { useEffect } from "react";
 
function App() {
 
    useEffect(() => {
            .then(response => response.json())
            .then(json => console.log(json))
    }, []);
 
    return (
        <div>
            Different ways to fetch Data
        </div>
    );
}
 
export default App;


Output: Now open localhost:300 and in the console, the data is fetched.

2. Fetch data using API using Axios Package:

Axios is a promise-based HTTP client designed for Node.js and browsers. With Axios, we can easily send asynchronous HTTP requests to REST APIs and perform create, read, update and delete operations. It is an open-source collaboration project hosted on Github. It can be imported in plain Javascript or with any library accordingly. 

To install Axios write the following command:

npm i axios

Javascript




// Filename - App.js
 
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>
            Different ways to fetch Data
        </div>
    );
}
 
export default App;


Output: Now open localhost:300 and in the console, the data is fetched.

3. Fetch data using API with Async-Await:

Async-Await is the preferred way of fetching the data from an API.

Async:

Async simply allows us to write promise-based code as if it was synchronous and it checks that we are not breaking the execution thread. It operates asynchronously via the event loop. Async functions will always return a value.

Await:

Await function is used to wait for the promise. It could be used within the async block only. It makes the code wait until the promise returns a result. It is used to prevent call-back hell and we can use it with Axios rather than the fetch method as Axios makes our code look cleaner and also makes it shorter(as we don’t need to convert to JSON format).

Javascript




// Filename - App.js
 
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 >
            Different ways to fetch Data
        </div>
    );
}
 
export default App;


Output: Now open localhost:300 and in the console, the data is fetched.

4. Using Custom hook:

Create one file(useFetch.js) for your custom hook which returns the state of important parameters like data, loading, and error. App.js file will import this hook

Import the useFetch hook and pass the URL of the API endpoint from where you want to fetch data.

App.js

Javascript




// Filename - App.js
 
import { useEffect } from "react";
import useFetch from "useFetch.js";
 
function App() {
    const { data: dataInfo, loading, error, refetch } = useFetch(
        https://jsonplaceholder.typicode.com/todos
    );
 
    return (
        <div >
            Different ways to fetch data
            {console.log(data)}
        </div>
    );
}
 
export default App;


Javascript




//Filename - useFetch.js
 
import { useEffect, useState } from "react";
import axios from "axios";
 
function useFetch(url) {
    const [data, setData] = useState("");
    const [loading, setLoading] = useState(false);
    const [error, setError] = useState("");
 
    useEffect(() => {
        setLoading(true);
        axios
            .get(url)
            .then((response) => {
                setData(response.data);
            })
            .catch((err) => {
                setError(err);
            })
            .finally(() => {
                setLoading(false);
            });
    }, [url]);
 
    const refetch = () => {
        setLoading(true);
        axios
            .get(url)
            .then((response) => {
                setData(response.data);
            })
            .catch((err) => {
                setError(err);
            })
            .finally(() => {
                setLoading(false);
            });
    };
 
    return { data, loading, error, refetch };
}
 
export default useFetch;


Output: Now open localhost:300 and in the console, the data is fetched.



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads