Jsonplaceholder 활용법

2023. 12. 6. 01:00

간단한 더미 json 데이터 Jsonplaceholder를 활용하는 법

 

JSONPlaceholder - Free Fake REST API

{JSON} Placeholder Free fake API for testing and prototyping. Powered by JSON Server + LowDB. Tested with XV. Serving ~2 billion requests each month.

jsonplaceholder.typicode.com

 

const getData = async()=> {
const res = await fetch('url').then(res=>res.json());
const initData = res.slice(0,20).map(item=> {
return {
    author : item.email,
    content : item.body,
    emotion : Math.floor(Math.random()*5)+1,
    crated_data : new Data().getTime(),
    id : dataId.current++,
}
})
setData(initData)
}


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

- 사용한  json데이터가 500개이기 때문에 initData라는 배열을 새로 만들어서 0~20개까지 slice한 후에 map으로 새로운 배열로 리턴했다. 기존에 사용중인 key값에 json데이터의 key를 item.key형식으로 써서 대응했다.

- Math.floor(Math.random() * 5) + 1
emotion은 1~5까지의 수를 랜덤하게 출력하고자
0~4까지의 랜덤한 수를 만드는 Math.random()*5를 Math.floor로 정수로 바꿔준 뒤에 1을 더했다.

- const dataId = useRef(0);로 초기값을 0으로 설정해두고, dataId.current에서 1씩 증가하는 방식으로 서로 다른 id를 구현했다.

- 이렇게 가공한 initData를 useState를 이용해서 API데이터를 호출했다. 

- 컴포넌트가 마운트 되었을 때 바로 호출할 수 있도록 useEffect에 빈배열을 두고, 마운트 지점에 getData가 호출되게 설정해두었다. 

'React' 카테고리의 다른 글

context Api  (0) 2023.12.21
useEffect  (0) 2023.12.19
useState 한꺼번에 정리하기  (0) 2023.12.05
(React) 리액트 기초 19. Firebase로 구글 로그인 하기  (0) 2023.08.09
(React) 리액트 기초 18. Router 설정  (0) 2023.08.09