react fetch, async,api

권슬기·2023년 6월 29일
0

react

목록 보기
14/17
const getData = async () => {
    const res = await fetch(
      "https://jsonplaceholder.typicode.com/comments"
    ).then((res) => res.json());

    const initData = res.slice(0, 20).map((it) => {
      return {
        author: it.mail,
        content: it.body,
        emotion: Math.floor(Math.random() * 5) + 1,
        created_date: new Date().getTime(),
        id: dataId.current++,
      };
    });

    setData(initData);
  };

  useEffect(() => {
    getData();
  }, []);

화면이 로딩 될 때 getData를 불러오면서 await fetch,async를 통해 api를 가져올 수 있다. console.log(res)하면 결과를 볼 수 있다. 해당 api는 가져오는 값이 500개여서 res.slice를 통해 20개로 자르고 map을 통해 원하는 정보를 내가 원하는 값에 기초 값으로 넣어 setData에 넣었다.

profile
병아리 프론트엔드 개발자

0개의 댓글

관련 채용 정보