DEV Community

Cover image for Different Ways to Fetch Data in React Js:
Bhartee Rameshwar Sahare
Bhartee Rameshwar Sahare

Posted on

Different Ways to Fetch Data in React Js:

Fetch Method:

The fetch() method in js is used to request the server and load the information in the web pages. The request can be any API that returns the date of the format JSON or XMLDocument. This method is returned as a Promise.

function App() {
    useEffect(() => {
        fetch('https://site.com/')
        .then(response => response.json())
        .then(json => console.log(json))
    }, []);

    return(
        <div> Fetch method used for fetching the data</div>
    );

}
Enter fullscreen mode Exit fullscreen mode

Async-Await:

This is the preferred way of fetching the data from an API as it enables us to remove our .then() callback and return asynchronously resolved data. For the async block, we can use the await function to wait for the Promise.

function App() {
    useEffect(() =>{
        (async () => {
            try {
                const result = await.axiox.get('https://site.com/')
                console.log(result.data)
            } catch (error){
                console.error(error)
            }
        })()
    })
    return <div> Async-Await method used for fetch the data</div>
}
Enter fullscreen mode Exit fullscreen mode

Axios library:

With axiox, we can easily send an asynchronous HTTP request to REST APIs & perform create, read, update, and delete operations. Axios can be imported in plain javascript or with any library accordingly.

function App(){
     useEffect(() => {
        axiox.get('https://site.com/')
        .then((response) => console.log(response.data));
     }, [])
     return(
        <div> Axios library used for fetch the data</div>
     )
}

Enter fullscreen mode Exit fullscreen mode

Custom Hook:

It is basically a react component whose name will start with use like useFetch. One or more React hooks can be used inside them.

const useFetch =(url) => {

    const [isLoading, setIsLoading] = useState(false)
    const [apiData, setApiData] = useState(null)
    const [ serverError, setServerError] = useState(null)

    useEffect(() => {
        setIsLoading(true)
        const fetchData = async () => {
            try {
                const resp = await.axiox.get(url)
                const data = await resp? data
                setApiData(data)
                setIsLoading(false)
            } catch(error){
                setServerError(error)
                setIsLoading(false)
            }
        }
        fetchData()
    }, [url])
    return { isLoading, apiData, serverError}

}
Enter fullscreen mode Exit fullscreen mode

Usage of the component:

Import the UseFetch hook and pass the URL of the API endpoint from where you want to fetch data.Now, just like any react hook, we can directly use our Custom hook to fetch the data.

import useFetch from './useFetch';

const App = () {
    const {isLoading, serverError, apiData} = useFetch('https://site.com')

    return(
        <div>
            <h2>Api Data</h2>
            { isLoading && <span>Loading......</span>}
            {isLoading  && serverError ? (
                <span>Error in fetching data...</span>
            ) : (
                <span>{JSON.stringify{apiData}}</span>
            )}
        </div>
    )
}
Enter fullscreen mode Exit fullscreen mode

Request Query library:

With this, we can achieve a lot more than just fetching data. It provides support for catching and re-fetching, which impacts the overall user experience by preventing irregularities and ensuring our app feels faster.

import axios from "axios";
import {useQuery}  from 'react-query'

function App() {
    const { isLoading, error, data} =
    useQuery('posts', () => axios('https://site.com'))
    console.log(data)
    return <div> Request query library to fetch the data</div>
}
Enter fullscreen mode Exit fullscreen mode

Top comments (1)

Collapse
 
vulcanwm profile image
Medea

Great article for someone who’s a beginner in React (like me)!