My Study/React

[React] - 비동기(fetch함수)

handbefore 2024. 10. 19. 15:45
fetch('API주소')
.then((response) => response.json())
.then((data) => console.log(data));

 

fetch함수

  • Response 객체로 데이터를 가져옴.
  • 실제 필요한 json 본문 데이터를 추출해주기 위해 json( ) 메서드를 사용해 변환 필요.

Promise

  • 비동기 작업이 완료, 실패 했을 때 처리하기 위한 객체.
  • 자바스크립트에 기본적으로 내장되어 있는 객체.
  • '대기' '이행' '거부' 상태로 표현

 

fetch 함수

  • Promise 인스턴스(then, catch, finally)

 

then 메서드

  • Promise 상태가 이행, 거부 상태가 되었을 때 실행. => 비동기 작업이 처리되었을 때 실행

 

동기화를 하는 시점은 데이터를 불러오는 데 성공했을 때

fetch('/product')
.then((response) => response.json())
.then((data) => setProducts(data.products));