[์‹ค์Šต] How many coins I can buy

arrrrrrยท2023๋…„ 2์›” 4์ผ

React ๊ณต๋ถ€์ค‘ ๐ŸŽฝ

๋ชฉ๋ก ๋ณด๊ธฐ
4/16

์š”๊ตฌ์‚ฌํ•ญ ์ •์˜

  • useEffect๋ฅผ ์‚ฌ์šฉํ•˜์—ฌ api๋Š” 1ํšŒ๋งŒ ๋ถˆ๋Ÿฌ์˜ค๊ธฐ
  • api ๋ถˆ๋Ÿฌ์˜ค๋Š” ๋™์•ˆ์€ ๋กœ๋”ฉํ™”๋ฉด ๋…ธ์ถœํ•˜๊ธฐ
  • ๋‚ด ์ž์‚ฐ๊ณผ ์ฝ”์ธ์„ ์„ ํƒํ•˜๋ฉด ๊ตฌ๋งค ๊ฐ€๋Šฅํ•œ ์ฝ”์ธ ๊ฐœ์ˆ˜ ์•Œ๋ ค์ฃผ๊ธฐ

์ž‘์„ฑ ์ฝ”๋“œ

์•Œ๊ฒŒ๋œ ์ 

  • option์˜ ๋ณ€๊ฒฝ์„ ๊ฐ์ง€ํ•˜๋ ค๋ฉด option์˜ ๋ถ€๋ชจ์š”์†Œ์ธ select์— onChange ์ด๋ฒคํŠธ๋ฅผ ๊ฑธ์–ด์ฃผ์–ด์•ผ ํ•œ๋‹ค.
  • useState์˜ ์ดˆ๊ธฐ๊ฐ’์œผ๋กœ ์ดˆ๊ธฐ๊ฐ’์„ ์ถ”์ ํ•  ์ˆ˜ ์žˆ๋‹ค. (๋‹น์—ฐํ•œ๋ฐ ๋‚˜๋Š” ๋ชฐ๋ž์ฅ ๐Ÿซ )
import { useEffect, useState } from 'react';

function Coin() {
    const [isLoading, setIsLoading] = useState(false);
    const [coins, setCoins] = useState([]);
    const [asset, setAsset] = useState();
    const [getCoin, setGetCoin] = useState(0);
    const onChangeAsset = (event) => setAsset(event.target.value);
    const onChangeGetCoin = (event) => setGetCoin(event.target.value);

    useEffect(() => {
        setIsLoading(true);
        fetch('https://api.coinpaprika.com/v1/tickers')
            .then((res) => res.json())
            .then((res) => {
                setCoins(res);
                setIsLoading(false);
            });
    }, [])

    return (
        <div>
            <h1>The Coins ({coins.length})</h1>
            <div>
                <input
                    type="text"
                    placeholder='Enter your asset here'
                    value={asset}
                    onChange={onChangeAsset} />
            </div>
            {isLoading ? <h3>Loading...</h3> : <select onChange={onChangeGetCoin}>
                {coins.map((el) => <option
                    key={el.id}
                    value={el.quotes.USD.price}>
                    {el.name}({el.symbol}): ${el.quotes.USD.price}
                </option>)}
            </select>}
            <div>
                YOU CAN BUY: {(asset !== undefined && getCoin > 0) ? (Number(asset) / getCoin).toFixed(3) : null}
            </div>
        </div>
    )
}

export default Coin
profile
โ›ฑ

0๊ฐœ์˜ ๋Œ“๊ธ€