- Fetch Methos
The Fetch() method in JS 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 formate JSON or XML. This method returns a promise.
function App(){
useEffect(()=>{
fetch('url-Link')
.then(response=>response.json())
.then(json=>console.log(json))
}, []);
return(
//code
);
}
- Async-Await
It is Preferred way of fetching the data from an API as it enables us to remove our .then() callbacks and return asynchronously resolved data. In the async block, we can use Await function to wait for the promise.
function App(){
useEffect(()=>
(async ()=>{
try{
const result = await.get('url')
console.log(result.data)
}catch (error){
console.error(error)
}
})()
})
return
<div>
//code
</div>
}
- Axios Library
With Axios, we can easily send asynchronous HTTP requests to REST APIs & perform create, read, update and delete operations. Axios can be imported in plain Javascript or with any library accourdingly.
function App(){
useEffect(()=>{
axios.get('link')
.then((res)=> console.log(res.data));
},[]);
return(
<div>
//code
</div>
}
- Custom Hook
it is basically a React component whose name will start with ‘use’ like useFetch . It can use one or more React hooks inside them.
import { useState, useEffect } from 'react';
// Custom hook for fetching data
function useDataFetching(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 (error) {
setError(error);
} finally {
setLoading(false);
}
};
fetchData();
}, [url]);
return { data, loading, error };
}
// Example usage in a component
function DataFetchingComponent() {
const apiUrl = '<https://api.example.com/data>';
const { data, loading, error } = useDataFetching(apiUrl);
if (loading) {
return <p>Loading...</p>;
}
- Usage in 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 React from 'react';
import useDataFetching from './useDataFetching'; // Assuming the custom hook is in a separate file
function DataFetchingComponent() {
const apiUrl = '<https://api.example.com/data>';
const { data, loading, error } = useDataFetching(apiUrl);
if (loading) {
return <p>Loading...</p>;
}
if (error) {
return <p>Error: {error.message}</p>;
}
return (
<div>
<h1>Data Fetched Successfully!</h1>
{/* Render your data here */}
<pre>{JSON.stringify(data, null, 2)}</pre>
</div>
);
}
export default DataFetchingComponent;
- React Ouery library
with this we can achieve a lot more than just fetching data. it provode support for caching and refetching, which impacts the overall user experience by preventing irregularities and ensuring our app feels faster.
npm install react-query
import React from 'react';
import { useQuery } from 'react-query';
function App(){
const {isLoading , error, data}=
useQuery('post',()=>axios('<https://sitte.com>'))
console.log(data)
return (
<div>
<h1>React Query Example</h1>
</div>
);
}
Thanks for reading to the end; I hope you gained some knowledge.❤️🙌