React/영화웹서비스만들기
Coin Tracker 만들기
냠냠쿠
2024. 4. 18. 15:52
728x90
1. 간단하게 제목과 로딩 text를 만들어준다
import { useEffect, useState } from "react";
function App() {
const [loading, setLoading] = useState(true);
return (
<div>
<h1> The coins!</h1>
{loading ? <strong> Loading ...</strong> : null}
</div>
);
}
export default App;
2. API 가져오기
- 가장 처음으로 render 될 때 돌아가도록 설정
useEffect(() => {
fetch("https://jsonplaceholder.typicode.com/users");
}, []);
나는 회사 보안 정책상 링크가 열리지 않아서 https://jsonplaceholder.typicode.com/users 로 대체했다.
3. Response로부터 Json추출하기
const [loading, setLoading] = useState(true);
useEffect(() => {
fetch("https://jsonplaceholder.typicode.com/users")
.then((response) => response.json())
.then((json) => console.log(json));
}, []);
콘솔을 보면 데이터를 받아오는 것을 알 수 있다.
4. Data를 State에 넣어 화면에 보여주기
function App() {
const [loading, setLoading] = useState(true);
const [coins, setCoins] = useState([]);
useEffect(() => {
fetch("https://jsonplaceholder.typicode.com/users")
.then((response) => response.json())
.then((json) => {
setCoins(json);
//로딩을 false로 바꿔주기
setLoading(false);
});
}, []);
return (
<div>
<h1> The coins!</h1>
{loading ? <strong> Loading ...</strong> : null}
<ul>
{coins.map((coin) => (
<li>
{coin.name}({coin.username}) : {coin.address.street}
</li>
))}
</ul>
</div>
);
}
const [coins, setCoins] = useState([]);
여기서 useState() 를 하게되면 undefined 가 되어 아래쪽에서 길이를 나타낼 수 없이 때문에 비어있는 array의 기본값이 되도록 []를 넣어준다.
로딩시 select box 등이 보이지 않길 원한다면 삼항연산자의 false부분에 코드를 넣어주면 깔끔한 로딩 화면을 볼 수 있다.
<h1> The coins! {loading ? "" : `(${coins.length})`}</h1>
{loading ? (
<strong> Loading ...</strong>
) : (
<ul>
{coins.map((coin) => (
<li>
{coin.name}({coin.username}) : {coin.address.street}
</li>
))}
</ul>
)}
728x90