리액트 fetch/catch

서울IT코드정리 /kyChoi·2021년 11월 20일
0

리랙트

목록 보기
14/18
<script type="text/babel">
      const 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"
          ) //raw임, 일부러 에러내서 catch 문 사용
            .then(function (response) {
              return response.json();
            })//받아온 값이 response.json 형태
            .then(function (myJson) {//myJson으로 넘겨줌
              setData(myJson.data);
            })
            .catch((error) => {
              console.log(error);
              alert(error);
            });
        }, []);
        if (error != null) {
          return <p>There is some Error!</p>;
        }
        if (data == null) {
          return <p style={{ color: "red" }}>Loading...</p>;
        }

        return (
          <div>
            <p>people</p>

            {data.people.map((person) => (
              <>
                <span>name : {person.name}</span> &nbsp;
                <span>age : {person.age}</span>
                <br />
              </>
            ))}
          </div>
        );
      };
      ReactDOM.render(<App />, document.getElementById("root"));
    </script>
profile
건물주가 되는 그날까지

0개의 댓글