느려도 한걸음씩

React로 HTTP 요청 보내기 - (2) 본문

FE develop/React

React로 HTTP 요청 보내기 - (2)

hoj0806 2025. 3. 12. 12:48

저번 게시물에서는 fetch로 데이터를 받아보았다 이번에는 async await를 이용해 좀더 간결하게 데이터를 가져와보자

 

  useEffect(() => {
    async function fetchPlaces() {
    
    }
    
  }, []);


}

먼저 useEffect안에 async 함수를 선언한다

 

  useEffect(() => {
    async function fetchPlaces() {
      const response = await fetch("http://localhost:5000/places");
      const resData = await response.json();
      setAvailablePlaces(resData.places);
    }
    
  }, []);

후에 await 키워드를 붙여 data를 fething하고 state에 저장한다

 

 useEffect(() => {
    async function fetchPlaces() {
      const response = await fetch("http://localhost:5000/places");
      const resData = await response.json();
      setAvailablePlaces(resData.places);
    }
    fetchPlaces();
  }, []);

 그 후에 선언했던 함수를 밑에서 실행해주면 된다