React에서 api 호출하기

DOYOUNG·2023년 8월 3일
0

reactjs

목록 보기
8/15
post-thumbnail

React에서 api 호출하기

더미데이터를 받아올 수 있는 jsonplaceholder 사이트에서 api를 받아온다.

  // api 호출
  const getData = async() => {
    const res = await fetch('https://jsonplaceholder.typicode.com/comments').then((res)=>res.json());
    console.log(res);

    const initData = res.slice(0,20).map((it)=>{
      return {
        author : it.email,
        content : it.body,
        emotion : Math.floor(Math.random() * 5)+1, // random은 랜덤 숫자가 나오지만 정수가 아닐 수 있기 때문에 floor로 소숫점 버리고 정수만 뽑아줌
        created_date : new Date().getTime(),
        id : dataId.current++,
      };
    });

    setData(initData);
  };

  // 뒤에 빈 배열을 두면 컴포넌트가 마운트 되자마자 앞의 콜백함수가 실행됨
  // 컴포넌트 마운트 되는 시점에 api 호출 함수 실행
  useEffect(()=>{
    getData();
  },[])

데이터를 받아오는 getData 함수를 만들고, res에 fetch를 이용하여 api를 호출한다.

const res = await fetch('https://jsonplaceholder.typicode.com/comments').then((res)=>res.json());

initData에 불러온 데이터 중 index 0부터 19까지 20개의 데이터만 남기고, map으로 전체 배열을 순회하면서
전에 만들어둔 state명에 각각 데이터의 값을 부여해준다.
그렇게 map 함수로 배열의 모든 요소를 순회하며 콜백함수를 리턴한 값을 배열로 만들어서 initData의 값으로 넣는다.

const initData = res.slice(0,20).map((it)=>{
  return {
    author : it.email,
    content : it.body,
    emotion : Math.floor(Math.random() * 5)+1, // random은 랜덤 숫자(0-4까지)가 나오지만 정수가 아닐 수 있기 때문에 floor로 소숫점 버리고 정수만 뽑아줌
    created_date : new Date().getTime(),
    id : dataId.current++,
  };
});

data 상태를 관리하는 setData 함수에 initData 값을 부여해준다.

setData(initData);

useEffect를 이용해 컴포넌트가 마운트 되자마자 getData 함수가 실행되도록 한다.

useEffect(()=>{
  getData();
},[])
profile
프론트엔드 개발자 첫걸음

1개의 댓글

comment-user-thumbnail
2023년 8월 3일

좋은 정보 얻어갑니다, 감사합니다.

답글 달기