ReactJS/Basic

[ReactJS] TIL #11

Gaeun Lee 2022. 7. 21. 13:16

Coin Tracker App 만들기

 

Coin Tracker App을 만들기 위해서는 API를 사용해야 한다 

const [coins, setCoins] = useState([]); // api로 받은 코인들을 나타내기
useEffect (() => {
fetch("https://api.coinpaprika.com/v1/tickers")
  .then(response => response.json()) // response로부터 json 추출
  .then((json) => {
    setCoins(json) // json 값을 coins 배열에 담는다
  }); 
}, [])

useEffect()를 통해 API를 처음 한 번만 가져오게 하고 fetch()를 통해 api를 호출한다

response로 받은 json을 추출하여 이를 coins 배열에 담아주면 완성이다

 

 

만약 coin tracker api가 fetch되었는지 확인하고 싶다면 F12 > Network 탭에 들어갔을 때 tickers 파일이 있는지 확인하면 된다

 

 

완성본

App.js

import { useState,useEffect } from "react"; 

function App() {
  const [loading, setLoading] = useState(true);
  const [coins, setCoins] = useState([]); // api로 받은 코인들을 나타내기
  useEffect (() => {
    fetch("https://api.coinpaprika.com/v1/tickers")
      .then(response => response.json()) // response로부터 json 추출
      .then((json) => {
        setCoins(json) // json 값을 coins 배열에 담는다
        setLoading(false) // coins를 모두 얻었으면 loading을 false로 바꾼다
      }); 
  }, [])
  return (
    <div className="App">
      <h1>Coin Tracker ({coins.length})</h1>
      {loading ? <strong>Loading...</strong> : null}
      <ul>
        {coins.map((coin) => (
          <li key={coin.id}>{coin.name} ({coin.symbol}): ${coin.quotes.USD.price} USD</li>
        ))} {/* 각각의 coin이 가진 json의 정보를 나타낸다 */}
      </ul>
    </div>
  );
}

export default App;