![article thumbnail image](https://blog.kakaocdn.net/dn/cpJOcC/btrGPnux289/AdLZ1Clf1RTQaC2VnEIUsk/img.png)
컴포넌트가 mount 되는 시점에 API를 호출하고 해당 데이터 결과값을 일기데이터값으로 초기화하는 기능을 만들어보자
자바스크립트 내장함수인 batch 사용할 예정
JSONPlaceholder - Free Fake REST API
{JSON} Placeholder Free fake API for testing and prototyping. Powered by JSON Server + LowDB. Tested with XV. As of Oct 2021, serving ~1.7 billion requests each month.
jsonplaceholder.typicode.com
JSONPlaceholder 를 이용해서 API를 사용할 것
이중 comments 리소스를 가지고 테스트해볼것
API를 호출하려면 주소를 알아야한다.
https://jsonplaceholder.typicode.com/comments
const getData = async () => {
const res = await fetch('https://jsonplaceholder.typicode.com/comments').then((res) => res.json());
}
await와 fetch를 같이 이용할 것이기 때문에 async를 이용해서 getData가 promise를 반환하는 비동기 함수가 되도록 해준다.
useEffect(() => {
getData(); //API 호출
}, []);
콘솔로 출력해주면
컴포넌트가 마운트 되는 시점에 API 데이터가 출력된 것을 알 수 있다
이제 이 값들을 일기데이터에 맞춰서 넣어볼 것
이제 이 불러온 API배열의 갯수를 자르고, map을 통해서 값을 일기장에 맞춰 넣어줄 것이다.
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,
created_date: new Date().getTime(),
id: dataId.current++
}
});
setData(initData);
}
참고 :
- 한 입 크기로 잘라먹는 리액트
반응형
'개발 > Javascript' 카테고리의 다른 글
[React] 최적화 - 연산 결과 재사용 (0) | 2022.07.13 |
---|---|
[React] React Developer Tools (0) | 2022.07.12 |
[React] 라이프사이클 제어하기 (0) | 2022.07.08 |
[React] 일기장에 추가한 배열 데이터 수정하기 (0) | 2022.07.07 |
[React] 일기장에 추가한 배열 데이터 삭제하기 ; 프롭스 드릴링? (0) | 2022.07.06 |