useEffect를 활용하여 데이터 fetch하기

kyeongboo·2023년 5월 18일

useEffect를 활용하여 데이터 fetch하는 방법은?

먼저 React 파일을 생성 후 생성한 파일 안에 data라는 폴더명의 파일을 하나 더 만듭니다.
그 다음 터미널에 다음 명령어를 입력하여 서버를 실행시켜줍니다.

json-server --watch ./data/db.json

json server란 간단한 DB와 API를 생성시켜주는 패키지입니다.

다음은 살짝 내용이 변경된 아래 코드 내용을 data 폴더 안에 db.json파일을 추가로 만들어서 작성합니다.

{
    "nations": [
        {
            "id": 1,
            "title": "France",
            "population": "100",
            "loc": "europe"
        },
        {
            "id": 2,
            "title": "Italy",
            "population": "200",
            "loc": "europe"
        },
        {
            "id": 3,
            "title": "England",
            "population": "300",
            "loc": "europe"
        },
        {
            "id": 4,
            "title": "USA",
            "population": "400",
            "loc": "america"
        },
        {
            "id": 5,
            "title": "Korea",
            "population": "500",
            "loc": "asia"
        }
    ]
}
import React, { useEffect, useState } from "react";
import styled from "styled-components";

const Item = styled.div`
  margin: 60px auto;

  ul {
    padding: 10px;
  }

  li {
    margin: 20px 0;
    padding: 10px;
    border: 1px solid black;
    box-sizing: border-box;
    border-radius: 10px;
    list-style: none;
    box-shadow: 4px 4px 6px rgba(0, 0, 0, 0.1);
  }
`;

export default function NationList() {
  const [nations, setNations] = useState([]);
  const [url, setUrl] = useState("http://localhost:3000/nations");

  useEffect(() => {
    fetch("http://localhost:3000/nations")
      .then((response) => {
        //    http 상태코드가 200번때가 아닐 경우
        if (!response.ok) {
          throw new Error("네트워크 응답에 문제가 있습니다.");
        }
        return response.json();
      })
      .then((json) => {
        console.log(json);
        setNations(json);
      })
      .catch((error) => {
        console.error("데이터를 가져오는데 문제가 발생했습니다 : ", error);
      });
  }, []);

  return (
    <Item>
      <h2>나라 목록</h2>
      <ul>
        {nations.map((nations) => {
          return (
            <li key={nations.id}>
              <h3>나라 이름 : {nations.title}</h3>
              <p>인구 수 : {nations.population}</p>
            </li>
          );
        })}
      </ul>
      <div>
        <button
          onClick={() => {
            setUrl("http://localhost:3000/nations?loc=europe");
          }}
        >
          유럽 목록
        </button>
        <button
          onClick={() => {
            setUrl("http://localhost:3000/nations");
          }}
        >
          전체 목록
        </button>
      </div>
    </Item>
  );
}

styled-components를 추가하여 스타일을 만들어주고 그 다음

  useEffect(() => {
    fetch("http://localhost:3000/nations")
      .then((response) => {
        //    http 상태코드가 200번때가 아닐 경우
        if (!response.ok) {
          throw new Error("네트워크 응답에 문제가 있습니다.");
        }
        return response.json();
      })
      .then((json) => {
        console.log(json);
        setNations(json);
      })
      .catch((error) => {
        console.error("데이터를 가져오는데 문제가 발생했습니다 : ", error);
      });
  }, []);

위 코드 내용 중 [ ] 와 같이 의존성 배열이 비어있을 때는 첫번째 렌더링 후에만 호출이 됩니다.

위 코드를 async/await 함수를 사용해서 바꿔보았습니다.

useEffect에서 async/await 사용하는 방법

import React, { useEffect, useState } from "react";
import styled from "styled-components";

const Item = styled.div`
  margin: 60px auto;

  ul {
    padding: 10px;
  }

  li {
    margin: 20px 0;
    padding: 10px;
    border: 1px solid black;
    box-sizing: border-box;
    border-radius: 10px;
    list-style: none;
    box-shadow: 4px 4px 6px rgba(0, 0, 0, 0.1);
  }
`;

export default function NationList() {
  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();

        setNations(json);
      } catch (error) {
        console.error("데이터를 가져오는데 문제가 발생했습니다 : ", error);
      }
    };

    fetchData();
  }, [url]);

  return (
    <Item>
      <h2>나라 목록</h2>
      <ul>
        {nations.map((nations) => {
          return (
            <li key={nations.id}>
              <h3>나라 이름 : {nations.title}</h3>
              <p>인구 수 : {nations.population}</p>
            </li>
          );
        })}
      </ul>
      <div>
        <button
          onClick={() => {
            setUrl("http://localhost:3000/nations?loc=europe");
          }}
        >
          유럽 목록
        </button>
        <button
          onClick={() => {
            setUrl("http://localhost:3000/nations");
          }}
        >
          전체 목록
        </button>
      </div>
    </Item>
  );
}
  useEffect(() => {
    const fetchData = async () => {
      try {
        const response = await fetch(url);

        if (!response.ok) {
          throw new Error("네트워크 응답에 문제가 있습니다.");
        }
        const json = await response.json();

        setNations(json);
      } catch (error) {
        console.error("데이터를 가져오는데 문제가 발생했습니다 : ", error);
      }
    };

    fetchData();
  }, [url]);

위 코드 내용 중 [url] 와 같이 의존성 배열에 값이 있을 경우에는 해당 값이 변경될때마다 호출됩니다.

profile
적극성과 커뮤니케이션 능력이 겸비된 개발자로 성장하자!

0개의 댓글