Different Ways to Fetch Data in React Js:

Valentsea
Total
0
Shares



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(
        
Fetch method used for fetching the data
); }
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 
Async-Await method used for fetch the data
}
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(
        
Axios library used for fetch the data
) }
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(
        

Api Data

{ isLoading && Loading......} {isLoading && serverError ? ( Error in fetching data... ) : ( {JSON.stringify{apiData}} )}
) }
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 
Request query library to fetch the data
}
Enter fullscreen mode

Exit fullscreen mode

Total
0
Shares
Valentsea

🏝️ i18n translations in Next.js 13’s app-dir for server/client components 🌊

Original article: https://aralroca.com/blog/i18n-translations-nextjs-13-app-dir In this post, I will explain how to easily load and use translations in the…