<aside> 💡 **세부 목표

useEffect를 이용하여 컴포넌트 Mount 시점에 API를 호출하고 해당 API의 결과 값을 일기 데이터의 초기 값으로 이용하기**

</aside>

요청할 API

App.js

fetch를 이용해서 해당 API로 요청하여 json데이터를 가져와 가공해서 뿌림

실행 기준은 useEffect를 이용하여 mount 됐을 때 실행되게 함

import { useEffect, useRef, useState } from "react";
import "./App.css";
import DiaryEditor from "./DiaryEditor";
import DiaryList from "./DiaryList";
import LifeCycle from "./Lifecycle";

// <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());

    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,
    };
    console.log("newItem : ", newItem);
    dataId.current += 1;
    setData([newItem, ...data]); //원래 데이터 를 가져오고 새로운 item은 최상단에 나오도록 함
  };

  const onDelete = (targetId) => {
    console.log(`${targetId}가 삭제되었습니다.`);
    // filter 이용해서 삭제할 Id에 대한 일기 빼고 해당 객체 리스트 가져옴
    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">
      {/* <LifeCycle /> */}
      <DiaryEditor onCreate={onCreate} />
      <DiaryList onEdit={onEdit} onDelete={onDelete} diaryList={data} />
    </div>
  );
}

export default App;

Untitled