728x90
https://jsonplaceholder.typicode.com/
https://jsonplaceholder.typicode.com/comments
App.js
- API 호출 코드 getData작성
- mount될 때 나와야 하는 데이터 > useEffect 사용(빈배열)
- 초기 데이터 initData 설정
import { useState, useRef, useEffect } from "react";
import "./App.css";
import DiaryEditor from "./DiaryEditor";
import DiaryList from "./DiaryList";
// https://jsonplaceholder.typicode.com/comments
function 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());
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);
};
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) => {
console.log(`${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 onRemove={onRemove} diaryList={data} onEdit={onEdit} />
</div>
);
}
export default App;
728x90
'🤯TIL > React' 카테고리의 다른 글
[React] async와 await를 사용한 CRUD (0) | 2023.11.30 |
---|---|
[한입 크기로 잘라 먹는 리액트] simpleDiary 코드 (1) | 2023.11.19 |
[한입 크기로 잘라 먹는 리액트] React Lifecycle 제어하기 - useEffect (1) | 2023.11.19 |
[한입 크기로 잘라 먹는 리액트] React에서 배열 사용하기 4 - 데이터 수정하기 (1) | 2023.11.19 |
[한입 크기로 잘라 먹는 리액트] React에서 배열 사용하기 3 - 데이터 삭제하기 (0) | 2023.11.19 |