fetch - response.json()이 undefined로 뜰 때

da.circle·2023년 3월 27일
0

fetch로 API 요청을 하던 중에, status 코드를 가져오고 싶었다.
그래서 다음과 같이 코드를 짰다.

fetch(url)
  let status;
  .then(response => {
    status = response.status;
    response.json();
  })
  .then(data => {
    console.log(data)
  })

하지만 생각과는 다르게 콘솔에는 undefined가 떴다..

찾아보니 fetch는 비동기 작업이고, Promise 객체를 반환한다고 한다.
response.json()을 중괄호로 감싸게 되면 반환되는 Promise객체가 없어서 undefined가 뜨는 것 같다.

만약 위 코드처럼 response를 사용한 로직이 여러 줄이라면 response.json()을 return하면 된다.

fetch(url)
  let status;
  .then(response => {
    status = response.status;
    return response.json();
  })
  .then(data => {
    setDetailContent(data);
    console.log(status); // 200
  })
  .catch(() => {
    alert('데이터를 불러오지 못했습니다. 잠시 후 다시 시도해주세요.');
});
profile
프론트엔드 개발자를 꿈꾸는 사람( •̀ ω •́ )✧

0개의 댓글