import React from 'react';
import { useState, useEffect } from 'react';
import ReactDOM from 'react-dom/client';
import reportWebVitals from './reportWebVitals';
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>COins!</h1>
{ loading? <strong> Loading ... </strong> : null }
{ loading? null :
<div>
<select>
{coins.map( (coin, index) => <option key={index} value={coin.name}>{coin.name} ({coin.symbol}) : {coin.quotes.USD.price} </option>)}
</select>
</div>
}
</div>
)
}
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(<App />)
reportWebVitals();
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);
}
)}, [] )
- 로딩 상태를 구현하기 위한 loading, setLoading을 useState로 설정한다.
- 코인 정보를 담을 coins, setCoins를 useState로 설정한다.
- useEffect 구문에서, 마지막 [] 빈 배열을 두었기 때문에 감시할 대상이 없다. 즉
- 코드가 한 번 실행되고 다시 실행되지 않는다.
- 이는 4000여개의 coin정보를 api에서 받아오기 때문에, 렌더링 될 때 마다 갱신된다면 로딩시간이
- 매우 비효율적으로 길 것이다. 그렇기에 useEffect를 적용시켜 준다.
- API를 통해 코인 정보가 다 받아와진 경우에, setLoading(false)를 통해 값을 변경해주어 렌더링이 나타날 수 있게 해준다.
return(
<div>
<h1>COins!</h1>
{ loading? <strong> Loading ... </strong> : null }
{ loading? null :
<div>
<select>
{coins.map( (coin, index) => <option key={index} value={coin.name}>{coin.name} ({coin.symbol}) : {coin.quotes.USD.price} </option>)}
</select>
</div>
}
</div>
)
- loading가 true이면 Loading...을 실행하고, false인 경우 null, 즉 해당 문구를 가린다.
- coins 배열을 받아서, <option></option> 태그내에서 요소들이 구성된다.
'Front-end > React.Js' 카테고리의 다른 글
[nomad coder] 리액트 기초 7 - 총정리 (0) | 2022.11.26 |
---|---|
[nomad coder] 리액트 기초 4 - todo list 만들기 (0) | 2022.11.25 |
[nomad coder] 리액트 기초 3 - 번외(Cleanup Function) (0) | 2022.11.24 |
[nomad coder] 리액트 기초 3 (0) | 2022.11.24 |
[nomad coder] 리액트 기초 2 (0) | 2022.11.24 |
댓글