npm install -g json-server
dbํด๋๋ฅผ ์์ฑํ๊ณ , db.json์ json๋ฐ์ดํฐ๋ฅผ ๋ฃ์ ํ
json-server --watch data/db.json
localhost:3000/nations์ ๋ค์ด๊ฐ๋ฉด db.json์ nations ๋ฐฐ์ด์ด ๋ค์ด๊ฐ์๋ค.
localhost:3000/nations/2
localhost:3000/nations?loc=europe
const [nations, setNations]=useState([]);
const [url, setUrl] = useState("http://localhost:3000/nations")
useEffect(()=>{
const fetchData = async() =>{
try {
const response = await fetch(url);
if(!response.ok){
throw new Error("๋คํธ์ํฌ ์๋ต์ ๋ฌธ์ ๊ฐ ์๋ค")
}
const json = await response.json();
//response.json() ๋ ํ๋ก๋ฏธ์ค ๋ฐํํ๋ฏ๋ก ๊ธฐ๋ค๋ ค์ผํจ.
setNations(json);
} catch (error) {
console.error('๋ฐ์ดํฐ๋ฅผ ๊ฐ์ ธ์ค๋๋ฐ ๋ฌธ์ ๊ฐ ๋ฐ์ํ์ต๋๋ค.',error)
}
}
fetchData();
},[url]);
import styled from "styled-components"
//styled ์ปดํฌ๋ํธ๋ ์ปดํฌ๋ํธ์ด๊ธฐ๋๋ฌธ์ ๋๋ฌธ์๋ก์จ์ฃผ์
const Item = styled.div`
margin: 60px auto;
ul{
padding: 10px;
}
li{
margin: 20px 0;
border: 1px solid black;
box-sizing: border-box;
padding: 10px;
border-radius: 10px;
list-style: none;
box-shadow: 4px 4px 6px rgba(0,0,0,0.1);
}
`
<Item>
<h2>๋๋ผ ๋ชฉ๋ก</h2>
<ul>
{nations.map((nation)=>{
return <li key={nation.id}>
<h3>๋๋ผ ์ด๋ฆ : {nation.title}</h3>
<p>์ธ๊ตฌ ์ : {nation.population}</p>
</li>
})}
</ul>
<div>
<button onClick={()=>{setUrl("localhost:3000/nations?loc=europe")}}>
์ ๋ฝ ๋ชฉ๋ก
</button>
<button onClick={()=>{setUrl("http://localhost:3000/nations")}}>
์ ์ฒด ๋ชฉ๋ก
</button>
</div>
</Item>
5์ 17์ผ ์์