json server

ํฌ๋กฑยท2023๋…„ 5์›” 19์ผ
0

React

๋ชฉ๋ก ๋ณด๊ธฐ
6/18
post-thumbnail

๐ŸŽ… ์ผ๋‹จ ์„ค์น˜

npm install -g json-server

dbํด๋”๋ฅผ ์ƒ์„ฑํ•˜๊ณ , db.json์— json๋ฐ์ดํ„ฐ๋ฅผ ๋„ฃ์€ ํ›„

json-server --watch data/db.json 

localhost:3000/nations์— ๋“ค์–ด๊ฐ€๋ฉด db.json์˜ nations ๋ฐฐ์—ด์ด ๋“ค์–ด๊ฐ€์žˆ๋‹ค.

๐ŸŽ„ url ํ™œ์šฉํ•˜๊ธฐ

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]);

๐ŸŽ… ์ปดํฌ๋„ŒํŠธ styleํ•˜๊ธฐ

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);
    }
`

๐ŸŽ… return ๊ฐ’


<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์ผ ์ˆ˜์—…

profile
๐Ÿ‘ฉโ€๐Ÿ’ป์•ˆ๋…•ํ•˜์„ธ์š”๐ŸŒž

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