[React] [감정일기장] - 기초 API 호출

Suvina·2024년 2월 6일

React

목록 보기
7/22
post-thumbnail
//App.js

//https://jsonplaceholder.typicode.com/comments

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.email,
        content : it.body,
        
        //Math.random은 항상 소수점 반환하기 때문에 Math.floor 이용해 정수로 반환함
        emotion : Math.floor(Math.random() * 5) + 1,
        
        created_date : new Date().getTime(),
        
        //지금은 return이 바로 되기때문에 기존처럼 id +1 방식은 불가능함
        id : dataId.current++
      }
    })

    setData(initData);
}

재밌다..!

정리

  1. API를 호출해서 데이터를 불러옴 (const getData) -호출구문은 그냥 외우면 된다.
  2. 데이터를 필요한 모양으로 다듬어줌 (const initData)
  3. 다듬어준 데이터를 기존에 사용하고 있던 데이터 자리에 넣어줌 (setData(initData))
profile
개인공부

0개의 댓글