React - Fetch, Async, Await

React - Fetch, Async, Await

Fetch, Async, Await in React

Fetch

  • 네트워크 요청을 쉽게 활용할 수 있게 만들어준다.
  • React native에서는 Fetch API를 제공한다.
  • Fetch의 두 번째 인수는 사용자
  • fetch의 리턴값은 promise
fetch("https://api/...")
 .then(response => response.json())
 .then(json => console.log(json))
 .catch(err => console.log(err));
// post 요청보내기(method를 PUT, DELETE로 바꾸어 사용할 수 있음)
fetch("https://api/...", {
 method: 'POST',
 headers: {
  'Accept': 'application/json',
  'Content-Type': 'application/json',
 }
});

fetch('https://api/...', {
 method: 'POST',
 headers: {
  'Accept': 'application/json',
  'Content-Type': 'application/json',
 },
 body: JSON.stringify({ // 전달할 파라미터 입력(json을 문자열로 변환 후 전달하기 위해 stringify() 사용)
  siteUrl: 'webisfree.com',
  siteName: 'WEBISFREE',
 }),
});

Async, Await

  • 순차적으로 코드를 실행할 때 필요(자바스크립트는 비동기)
  • 동기 함수
  • promise, then를 사용해도 되지만 많이 사용하면 콜백루프(콜백헬)에 빠질 수 있음
  • await는 꼭 async함수 내부에서 사용, 에러남
  • promise 대신 사용할 수 있음(ES6)
function getApi() {
 const api = await fetch('https://api/...')
 .then(res => console.log(res));
}

async function getApi() {
 let response = await fetch('https://api/...');
 let responseJson = await response.json();
}
// 위와 아래는 같은 코드이다.

Why Use async/await?

  • 깔끔, 간결(기존의 promise, then을 사용했을 때보다 훨씬 코드가 짧아지고 보기 쉬워진다.)
  • 디버깅(디버깅이 매우 쉬워진다.)

댓글

가장 많이 본 글