6-5. 리스트 데이터 삭제하기 (DELETE)

2022. 7. 5. 09:11React/한입 크기로 잘라 먹는 리액트(React.js)

App.js

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

// const dummyList = [
//   {
//     id: 1,
//     author: "이정환",
//     content: "하이 1",
//     emotion: 5,
//     created_date: new Date().getTime(),
//   },
//   {
//     id: 2,
//     author: "홍길동",
//     content: "하이 2",
//     emotion: 2,
//     created_date: new Date().getTime(),
//   },
//   {
//     id: 3,
//     author: "아무개",
//     content: "하이 3",
//     emotion: 3,
//     created_date: new Date().getTime(),
//   },
// ];

const App = () =>  {
  // 전역적으로 Data 관리할 state
  const [data, setData] = useState([]);
  const dataId = useRef(0);

  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 onDelete = (targetId) => {
    console.log(`${targetId}가 삭제되었습니다.`);
    // filter 기능을 통해 그 부분만 빼고 출력 된다.
    const newDiaryList = data.filter((it) => it.id !== targetId);
    console.log(newDiaryList);
  }

  return (
    <div className="App">
      <DiaryEditor onCreate={onCreate} />
      <DiaryList onDelete={onDelete} diaryList={data} />
    </div>
  );
}

export default App;

DiaryList.js

import DiaryItem from "./DiaryItem";

const DiaryList = ({ onDelete, diaryList }) => {
  return (
    <div className="DiaryList">
      <h2>일기 리스트</h2>
      <h4>{diaryList.length}개의 일기가 있습니다.</h4>
      <div>
        {diaryList.map((it) => (
          <DiaryItem key={it.id} {...it} onDelete={onDelete} />
        ))}
      </div>
    </div>
  );
};

// defaultProps는 undefined로 전달 될 수 있는 값을 default로 설정해주는 것
DiaryList.defaultProps = {
    diaryList: []
}

export default DiaryList;

DiaryItem.js

const DiaryItem = ({ onDelete, author, content, created_date, emotion, id}) => {
    return (
      <div className="DiaryItem">
        <div className="info">
          <span className="author_info">
            작성자 : {author} | 감정: {emotion}
          </span>
          <br />
          <span className="date">
            {new Date(created_date).toLocaleString()}
          </span>
        </div>
        <div className="content">{content}</div>
        <button
          onClick={() => {
            console.log(id);
            if (window.confirm(`${id}번째 일기를 정말 삭제하시겠습니까?`)) {
              onDelete(id);
            }
          }}
        >삭제하기</button>
      </div>
    );
};

export default DiaryItem;

 

filter 기능을 통해 Delete 기능을 시행할 수 있다.

  const onDelete = (targetId) => {
    console.log(`${targetId}가 삭제되었습니다.`);
    // filter 기능을 통해 그 부분만 빼고 출력 된다.
    const newDiaryList = data.filter((it) => it.id !== targetId);
    console.log(newDiaryList);
  }