코딩/Today I Learn

React learning #7 Coin Tracker

코딩쪼렙 2022. 4. 6. 15:59
728x90

import { useState, useEffect } from "react";

 

function App() {

    const [loading, setLoading] = useState(true);

    const [coins, setCoins] = useState([]); //기본 값을 [] 배열로 설정하지 않으면 undefined가 되고 jsx에 undefined.length를 가져오게 되서 에러가난다.

    useEffect(() => {

        fetch("https://api.coinpaprika.com/v1/tickers?limit=100")

            .then((response) => response.json())

            .then((json) => {

                setCoins(json);

                setLoading(false);

            });

    }, []);

    return (

        <div>

            <h1>The Coins! {loading ? "" : `(${coins.length})`}</h1>

            {loading ? (

                <strong>Loading..</strong>

            ) : (

                <select>

                    {coins.map((coin) => (

                        <option>

                            {coin.name}({coin.symbol}):{coin.quotes.USD.price}{" "}

                            USD

                        </option>

                    ))}

                </select>

            )}

        </div>

    );

}

 

export default App;