내일배움캠프 6주차 TIL
내일배움캠프 6주차 6-4TIL (fetch, then useEffect)
YOOYOUNGJAE
2022. 12. 9. 15:02
728x90
오늘은 useEffect에 대해서 배웟따
아직까지는 확실하게 이해가가진않지만
fetch로 api가 담겨있는곳으로가서
response를 json 객체로 바꿔주고
그json값을 setCions로 값을 넣어준다
너무어렵다...
살려주세요,..
import React, { useEffect, useState } from 'react';
export default function App() {
const [loading, setLoading] = useState(true);
const [coins, setCions] = useState([]);
useEffect(() => {
fetch("https://api.coinpaprika.com/v1/tickers?limit=30")
.then((response) => response.json())
.then((json) => {
setCions(json);
setLoading(false);
})
}, []);
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}|</li>)}
</ul>
</div>
);
}
//코인 API에는 이미 key가 있으므로 안 가져와도 됨
//이 경우 coin이라는 변수는 coins 배열 안에 있는 각각의 coin을 의미함
//그래서 각각의 coin은 https://api.coinpaprika.com/v1/tickers 처럼 생겼음
//그래서 coin.name도 coin.symbol도 가져올 수 있음
//처음에는 기본값으로 비어있는 배열을 넘겨주기 때문에 coin이 처음엔 0개
//기본값을 적어도 빈값으로 정해주지 않으면 에러가 남
728x90