일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | 3 | 4 | 5 | ||
6 | 7 | 8 | 9 | 10 | 11 | 12 |
13 | 14 | 15 | 16 | 17 | 18 | 19 |
20 | 21 | 22 | 23 | 24 | 25 | 26 |
27 | 28 | 29 | 30 |
Tags
- tailwind
- useAppDispatch
- webpack
- ESlint
- recoil
- SSR
- app router
- 무한 스크롤
- 이분 검색
- TS
- 호이스팅
- 타입 좁히기
- dfs
- Cypress
- React
- Promise
- 공변성
- async/await
- Jest
- 반공변성
- CI/CD
- 투포인터
- 리터럴 타입
- autosize
- CORS
- 태그된 유니온
- RTK Query
- map
- 결정 알고리즘
- 인터섹션
Archives
- Today
- Total
짧은코딩
React에서 API 호출하기 본문
반응형
-API 호출을 위한 사이트
https://jsonplaceholder.typicode.com/
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
여기에는 어떤 API 서비스로 자원을 가져다가 쓸 수 있는지 리스팅을 해놨다. 이중에서 comments를 사용했다.
comments의 내용에서 이런 것을 활용해 데이터를 가공했다.
-App.js
import { useEffect, useRef, useState } from "react";
import "./App.css";
import DiaryEditor from "./DiaryEditor";
import DiaryList from "./DiaryList";
//https://jsonplaceholder.typicode.com/comments
const App = () => {
const [data, setData] = useState([]);
const dataId = useRef(0);
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,
created_date: new Date().getTime(),
id: dataId.current++,
};
});
setData(initData);
};
useEffect(() => {
getData();
}, []);
const onCreate = (author, content, emotion) => {
const created_date = new Date().getTime();
const newItem = {
author,
content,
emotion,
created_date,
id: dataId.current,
};
dataId.current += 1;
setData([newItem, ...data]);
};
const onRemove = (targetId) => {
const newDiaryList = data.filter((it) => it.id !== targetId);
setData(newDiaryList);
};
const onEdit = (targetId, newContent) => {
setData(
data.map((it) =>
it.id === targetId ? { ...it, content: newContent } : it
)
);
};
return (
<div className="App">
<DiaryEditor onCreate={onCreate} />
<DiaryList onEdit={onEdit} onRemove={onRemove} diaryList={data} />
</div>
);
};
export default App;
-수정한 부분
const App = () => {
const [data, setData] = useState([]);
const dataId = useRef(0);
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,
created_date: new Date().getTime(),
id: dataId.current++,
};
});
setData(initData);
};
useEffect(() => {
getData();
}, []);
API에서 불러와서 일기에 사용한다.
컴포넌트 마운트 시점에 getData라는 함수를 만들어서 async와 await을 사용해 데이터를 가공하여 일기의 기본값을 만들어봤다.
반응형
'인프런, 유데미 > 한입 크기로 잘라 먹는 리액트' 카테고리의 다른 글
최적화 1 - useMemo (0) | 2022.05.27 |
---|---|
React developer tools (0) | 2022.05.27 |
Lifecycle 제어하기 (0) | 2022.05.26 |
데이터 수정하기 (0) | 2022.05.25 |
데이터 삭제하기 (0) | 2022.05.25 |
Comments