-
목표
- 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
'Blog > React.js' 카테고리의 다른 글
[일기장 만들기_10] 최적화 1 - useMemo (연산 결과 재사용) (0) 2022.02.23 [일기장 만들기_09] React Developer Tools (0) 2022.02.23 [일기장 만들기_07] Lifecycle 제어하기 - useEffect (0) 2022.02.22 [일기장 만들기_06] 배열 사용하기 4 - 데이터 수정 (0) 2022.02.21 [일기장 만들기_05] 배열 사용하기 3 - 데이터 삭제 (0) 2022.02.17 댓글