Blog/React.js
[일기장 만들기_08] React에서 API 호출하기
용디
2022. 2. 22. 15:44
목표
- useEffect를 이용해 컴포넌트 Mount 시점에 API 호출
- 호출된 API 결과값을 일기테이터의 초기값으로 이용
사용 API
https://jsonplaceholder.typicode.com/comments
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
1. API 호출 함수 생성
2. 마운트 후 바로 실행할 수 있도록 처리
3. API데이터를 일기데이터로 사용 할 수 있도록 기초값 설정
👀 최종코드
~~~~~
function App() {
const [data, setData] = useState([]);
const dateId = useRef(0);
// 👉 API 호출 함수
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,
emotion : Math.floor(Math.random() * 5)+1, // 👉 1~5 까지의 랜덤한 숫자 생성
create_date : new Date().getTime(),
id : dateId.current++ // 👉 리턴 바로 되어버리니까 후의연산자로 1씩 증가 처리
}
});
setData(initData);
};
// 👉 마운트 후 바로 처리
useEffect(() => {
getData();
},[]);
~~~~~
💡 코드해석
- res.slice(0,20) ➡️ API Free 데이터 20개로 추리기
- map ➡️ 내장함수로 데이터 순회
- Math.random() * 5 ➡️ 0~4까지의 랜덤 난수를 생성
- Math.floor() ➡️ 정수가 반환되지 않기 때문에 소수점을 버리고 정수로 바꿔주기위해
- +1 ➡️ 1~5까지 나오게 처리
Demo : winterlood - CodeSandBox