React 맛보기 - 데이터 Fetch 해보기

lbr·2022년 8월 16일
0

Fetch API

기본 개념
https://developer.mozilla.org/ko/docs/Web/API/Fetch_API#%EA%B8%B0%EB%B3%B8_%EA%B0%9C%EB%85%90%EA%B3%BC_%EC%82%AC%EC%9A%A9_%EB%B0%A9%EB%B2%95

Fetch 사용하기
https://developer.mozilla.org/ko/docs/Web/API/Fetch_API/Using_Fetch

실습

실습용 api주소

https://raw.githubusercontent.com/techoi/raw-data-api/main/simple-api.json

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
  </head>
  <body>
    <script src="https://unpkg.com/react@17/umd/react.development.js"></script>
    <script src="https://unpkg.com/react-dom@17/umd/react-dom.development.js"></script>
    <script src="https://unpkg.com/@babel/standalone/babel.min.js"></script>
    <div id="root"></div>
    <script type="text/babel">
      const rootElement = document.getElementById("root");

      function App() {
        const [data, setData] = React.useState(null);
        const [error, setError] = React.useState(null);

        React.useEffect(() => {
          fetch(
            "https://raw.githubusercontent.com/techoi/raw-data-api/main/simple-api.json"
          )
            .then((response) => response.json())
            .then((mydata) => setData(mydata.data))
            .catch((error) => setError(error));
          // console.log(data);
        }, []);

        if (error !== null) {
          return <p>{error.message}</p>;
        }

        if (data == null) {
          return <p>Loading....</p>;
        }

        return (
          <>
            <div>
              <p>People</p>
              {JSON.stringify(data, null, 2)}
              {data.people.map((person) => (
                <div>
                  <span>name: {person.name}</span>
                  <p>age: {person.age}</p>
                </div>
              ))}
            </div>
          </>
        );
      }

      ReactDOM.render(<App />, rootElement);
    </script>
  </body>
</html>
if (data == null) {
  return <p>Loading....</p>;
}

보통은 이렇게 처리하지 않지만, 실습에서 이 부분이 없다면 api로 데이터를 가져오기 전에 먼저 데이를 map을 사용하여 출력하려 하므로 에러가 나옵니다.

정리

0개의 댓글