📌 Fetch API
Fetch API는 네트워크 통신을 포함한 리소스 취득을 위한 인터페이스가 정의되어 있다. XMLHttpRequest와 같은 비슷한 API가 존재하지만, 새로운 Fetch API는 좀 더 강력하고 유연한 조작이 가능하다. Fetch API는 HTTP 파이프라인을 구성하는 요청과 응답 등의 요소를 JavaScript에서 접근하고 조작할 수 있는 인터페이스를 제공한다. Fetch API가 제공하는 전역 fetch() 메서드로 네트워크의 리소스를 쉽게 비동기적으로 가져올 수도 있다.
Fetch API - Web API | MDN
Fetch API는 네트워크 통신을 포함한 리소스 취득을 위한 인터페이스가 정의되어 있습니다. XMLHttpRequest와 같은 비슷한 API가 존재합니다만, 새로운 Fetch API는 좀더 강력하고 유연한 조작이 가능합니
developer.mozilla.org
📌 사용 방법
일단 서버가 없으니 고정된 json 파일을 받아왔다.
아래 사진은 MDN 문서의 Fetch API 사용법이다.
이를 활용하여 fetch를 사용해 주소를 받아와 json.data 내용을 setData 해줬고, name과 age 를 그려줬다.
📌 오류 catch
다음으로, 없는 주소를 적으면서 아래처럼 오류를 발생시켜 보겠다.
.catch를 활용해 에러를 잡을 수 있다. error 상태를 만들고, setError를 활용해 상태 값을 변경해주는데 여기서 error 자체를 넣으면 돌아가지 않는다. error.message로 변경을 해줘야 제대로 작동하는 것을 볼 수 있다.
<script type="text/babel">
const root = document.querySelector("#root");
const App = () => {
const [data, setData] = React.useState(null);
const [error, setError] = React.useState(null);
React.useEffect(() => {
fetch(
"https://raw.githubusercontent.com/techoi/rawdata-api/main/simple-api.json"
)
.then(function (response) {
return response.json();
})
.then(function (myJson) {
setData(myJson.data);
})
.catch((error) => {
console.log(error);
setError(error.message);
});
}, []);
if (error !== null) {
return <p>{error}</p>;
}
if (data === null) {
return <p>Loading....</p>;
}
return (
<div>
<p>People</p>
{data.people.map((person, idx) => (
<div key={idx}>
<span>name: {person.name} </span>
<span>age: {person.age} </span>
</div>
))}
</div>
);
};
ReactDOM.render(<App />, root);
</script>
'🍞 Front-End > React' 카테고리의 다른 글
[React] Memoization (메모이제이션) (0) | 2022.10.25 |
---|---|
[React] 합성 이벤트(SyntheticEvent) (0) | 2022.10.22 |
[React] Error 다루기 (0) | 2022.10.21 |
[React] Ref로 DOM 다루기 & Form 다루기 (0) | 2022.10.21 |
[React] state변경 시, setState, useState 사용 이유 (0) | 2022.10.06 |