DEV Community

Drian
Drian

Posted on

Different Ways to Fetch Data in React JS

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>
 )
}
Enter fullscreen mode Exit fullscreen mode

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>
 )
}
Enter fullscreen mode Exit fullscreen mode

Axios Library

import axios from 'axios';

function App(){
 useEffect(() => {
  axios.get("https://site.com)
  .then((response) => console.log(response))
 }, [])

 return (
  <div>Axios Library</div>
 )
}
Enter fullscreen mode Exit fullscreen mode

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}
}
Enter fullscreen mode Exit fullscreen mode

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>
 )
}
Enter fullscreen mode Exit fullscreen mode

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>
 )
}
Enter fullscreen mode Exit fullscreen mode

Top comments (0)