API로 가상화폐 데이터 받아 처리하는동안 Loading 화면 처리

import { useEffect, useState } from "react"; function App() { const [loading, setLoading] = useState(true); const [coins, setCoins] = useState([]); useEffect(() => { fetch("https://api.coinpaprika.com/v1/tickers") // API를 이용해 fetch해서 response를 받아오는데, .then((response) => response.json()) // 시간이 걸리니 then 이후 response를 json 처리 .then((json) => { // 그리고 이 json으로 데이터 가공이 끝나면 setCoins(json); // 1. setCoins 함수로 coins에 json 데이터 저장 setLoading(false); // 2. setLoadings 함수로 loading을 false로 바꿈 }); }, []); return ( <div> <h1>The Coins!</h1> {loading ? <strong>Loading...</strong> : null} </div> ); } export default App;
  • loading state : API가 받아져서 화면에 render될 때까지 표시

  • loading이 최초값 true라면 화면에 Loading... 표시, 이후 false가 되면 null로 제거

  • coins state : API를 이용해 가공 처리한 json 데이터가 저장된 state

  • API 호출까지 시간이 걸리므로 **.then()**을 이용


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> );
  • json 데이터인 coins의 각각의 coin을 map함수로 처리
  • coin은 고유의 id를 가진 object 형태이므로 index는 별도로 불필요
  • coin.name, coin.symbol, coin.quotes.USD,price 등 json 파일에서 필요한 정보를 추출해 component화
  • 각각의 정보를 li 태그에 담고, 이를 ul 태그로 감싸기