Source: 🔍 6 Different Ways to Fetch Data in React | Muhammad Nouman
Fetch Method
function App(){
useEffect(() => {
fetch('https://site.com')
.then(response => response.json())
.then(json => console.log(json))
}, [])
return (
<div>Fetch Method</div>
)
}
Async-Await
function App(){
useEffect(() => {
(async () => {
try {
const result = await axios.get('https://site.com')
console.log(result)
} catch (error) {
console.log(error)
}
})()
}, [])
return (
<div>Async Await</div>
)
}
Axios Library
import axios from 'axios';
function App(){
useEffect(() => {
axios.get("https://site.com)
.then((response) => console.log(response))
}, [])
return (
<div>Axios Library</div>
)
}
Custom Hook
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 response = await axios.get(url)
const data = await response?.data
setApiData(data)
setIsLoading(false)
} catch (error) {
setServerError(error)
setIsLoading(false)
}
}
fetchData()
}, [url])
return {isLoading, apiData, serverError}
}
Usage in the Component
import useFetch from "./useFetch";
function App(){
const {isLoading, serverError, apiData} = useFetch('https://site.com')
return (
<div>
{isLoading && <span>Loading...</span>}
{!isLoading && serverError ? (
<span>Error in fetching data...</span>
) : (
<span>{JSON.stringify(apiData)}</span>
)}
</div>
)
}
React Query Library
import axios from 'axios';
const { useQuery } from 'react-query';
function App(){
const { isLoading, error, data } = useQuery('posts', () => axios('https://site.com'))
console.log(data)
return (
<div>React Query Library</div>
)
}
Top comments (0)