이번 시간에는 외부 Api로부터 정보를 얻어 와,
ReactJS를 이용하여 이를 사용한 서비스를 만들어 보았다.
우당탕탕 만든 느낌이 드나, 최선을 다해 만들어봤으니 코드리뷰를 해보도록,, 하겠다.
생각하기는 쉬울 것 같았는데,
막상 만들려하니 빡센 듯한 ㅋㅋ
import { useEffect, useState } from "react";
function App() {
const [loading, setLoading] = useState(true);
const [coins, setCoins] = useState([]);
const [money, setMoney] = useState(0);
const [coinPrice, setCoinPrice] = useState(0);
const [coinName, setCoinName] = useState("");
// calling Api (only once)
useEffect(() => {
// How to call Api by address
fetch("https://api.coinpaprika.com/v1/tickers")
.then((response) => response.json())
.then((json) => {
setCoins(json);
setLoading(false);
});
}, []);
function onChange (event) {
setMoney(event.target.value);
}
function getPriceAndName (event) {
const idx = event.target.selectedIndex;
setCoinPrice(coins[idx].quotes.USD.price);
setCoinName(coins[idx].id);
}
return (
<div>
<h1>The Coins! {loading ? "" : `(${coins.length})`}</h1>
{loading ? <strong> Loading... </strong> : (
<select
onChange={getPriceAndName}
>
{coins.map((coin, idx) => (
<option>
{coin.name} ({coin.symbol}) : {coin.quotes.USD.price} USD
</option>
))}
</select>)}
<input
type="number"
value={money}
onChange={onChange}
>
</input>
<p> {money && coinPrice ? `U can buy ${Math.round(money / coinPrice)} coins of ${coinName}` : "Please select the coin you want to buy and the budget"} </p>
</div>
)
}
export default App;
초기상태에서는 money와 coinPirce가 useState를 통해 default 값인 0과 ""
즉, boolean 연산 상 false의 값을 갖고 있기에,
"Please select the coin you want to buy and the budget" 문구가 UI에 표시된다.
<코인 코르기>
select는 변화할 때 (onChange) getPriceAndName함수를 불러온다.
이 getPriceAndName 함수는 이름 그대로 coin의 price와 name을 설정하고 UI를 초기화시킨다.
<예산 입력받기>
input 박스를 만들고, value는 money로 설정했다.
money는 useState를 이용하여 default 값을 0으로 설정했고,
input값이 바뀔 때마(onChange) onChange함수를 불러온다.
이 함수는 현 input 박스의 value를 money에다가 넣어주고 UI를 다시한번 불러온다. (useState의 특징)
<결과 띄우기>
이제 money와 coinPrice의 값이 설정되었으니 UI는 내가 살 수 있는 코인의 갯수와 선택한 코인의 이름을 보여준다.
'FrontEnd > React' 카테고리의 다른 글
[ReactJS] Params, Link (0) | 2023.01.13 |
---|---|
[ReactJS] Router (0) | 2023.01.13 |
[ReactJS] map() 매서드의 활용 (0) | 2023.01.12 |
[ReactJS] useEffect() 의 활용 (0) | 2023.01.11 |
[ReactJS] useEffect() (0) | 2023.01.11 |