본문 바로가기
개발/react

react의 useEffect는 api call 할 때 많이 사용!!

by 발명가H 2022. 9. 26.

코인 정보를 가져올 때

우선 useState는 로딩, 로딩후 상태 업데이트에 사용하고 true-> false

또한 코인 상태를 저장하는 것에 사용한다.  [] -> [코인 값 json]

 

그리고 useEffect는 코인 api를 fetch한 다음에 setLoading을 false로 바꿔준다.

 

그리고 html에는 각 coin의 목록을 li에 넣어준다.

import { useEffect, useState } from "react";


function App() {
  const [loading, setLoading] = useState(true);
  const [coins, setCoins] = useState([])
  useEffect(() => {
    fetch("https://api.coinpaprika.com/v1/tickers").then((response) => response.json()).then((json) => setCoins(json));
    setLoading(false)
  }, [])
  return (
    <div>
      <h1>The Coins! ({coins.length})</h1>
      {loading? <strong>Loading...</strong> : null}
      <ul>
        {coins.map((coin) => <li>{coin.name} ({coin.symbol}) : {coin.quotes.USD.price} USD</li>)}
      </ul>
    </div>
  );
}

export default App;