React 치트 코드에서 데이터 가져오기

12757 단어
API 크레딧 이동: johnsmilga( https://www.johnsmilga.com/ )

1) 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;


2) Axios 사용.
먼저 이 명령을 사용하여 axios를 설치하십시오. "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;



2) 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;

좋은 웹페이지 즐겨찾기