DEV Community

Mubasshir Ahmed
Mubasshir Ahmed

Posted on

Fetch Data in React Cheat Code

API credit goes to : johnsmilga (https://www.johnsmilga.com/)

1) fetch data using fetch api :

import { useState, useEffect } from 'react';

const url = 'https://course-api.com/react-tours-project';

function App() {
  const [tours, settours] = useState([])
  const [loading, setloading] = useState(true)

  // fetching data
  useEffect(() => {
    fetch(url)
    .then(response => {
      if(response.ok){
        return response.json()
      }
      throw response;
    })
    .then(tours => {
      settours(tours);
    })
    .catch(error => {
      console.error("Error Fetching",error);
    })
    .finally(()=>{
      setloading(false)
    })
  }, [])

if(loading){
    return(
      <main>
        <Loading/>
      </main>
    )
  }

  return (
    <div className="App">
     <Tours/>
    </div>
  );
}

export default App;
Enter fullscreen mode Exit fullscreen mode

2) using Axios.
firstly install axios using this command "npm install axios
"


import { useState, useEffect } from 'react';

const url = 'https://course-api.com/react-tours-project';

function App() {
  const [tours, settours] = useState([])
  const [loading, setloading] = useState(true)

  // fetching data
  useEffect(() => {
  axios(url)
  .then(response =>{
    settours(response.tours)
  })
  .catch(error => {
    console.error("Error Fetching",error);
  })
    .finally(() => {
      setloading(false)
    })
}, [])

if(loading){
    return(
      <main>
        <Loading/>
      </main>
    )
  }

  return (
    <div className="App">
     <Tours/>
    </div>
  );
}

export default App;

Enter fullscreen mode Exit fullscreen mode

2) using async/ await


import { useState, useEffect } from 'react';

const url = 'https://course-api.com/react-tours-project';

function App() {
  const [tours, settours] = useState([])
  const [loading, setloading] = useState(true)

  // fetching data

const fetchTours = async () => {
  setloading(true)
  try{
    const response = await fetch(url)
    const tours = await response.json()
    setloading(false)
    settours(tours)
  }catch(error){
    setloading(false)
    console.log(error)
  }
}

useEffect(() => {
  fetchTours()
}, [])

if(loading){
    return(
      <main>
        <Loading/>
      </main>
    )
  }

  return (
    <div className="App">
     <Tours/>
    </div>
  );
}

export default App;

Enter fullscreen mode Exit fullscreen mode

Top comments (0)