Language/React.js

[React] 감정일기장 프로젝트 : 일기 관리 기능 구현하기

JJcoding 2024. 10. 23. 13:28

일기 관리 기능 구현하기

App.jsx

import "./App.css";
...생략

const mockData = [
  {
    id: 1,
    createdData: new Date().getTime(),
    emotionId: 1,
    content: "1번 일기 내용",
  },
  {
    id: 2,
    createdData: new Date().getTime(),
    emotionId: 2,
    content: "2번 일기 내용",
  },
];

function reducer(state, action) {
  return state;
}

function App() {
  const [data, dispatch] = useReducer(reducer, mockData);
  return (
    <>
      ...생략
    </>
  );
}

export default App;
  • 모든 페이지에서 사용해야 할 일기 데이터인 data state를 상태 관리 코드인 reducer를 통해 생성하고 초기값인 mockData를 넣어준다
import "./App.css";
...생략

const mockData = [
 ...생략
];

function reducer(state, action) {
  switch (action.type) {
    case "CREATE":
      return [action.data, ...state];
    case "UPDATE":
      return state.map((item) =>
        String(item.id) === String(action.data.id) ? action.data : item
      );
    case "DELETE":
      return state.filter((item) => String(item.id) !== String(action.id));
    default:
      return state;
  }
}

function App() {
  const [data, dispatch] = useReducer(reducer, mockData);
  const idRef = useRef(3);

  // 새로운 일기 추가
  const onCreate = (createdData, emotionId, content) => {
    dispatch({
      type: "CREATE",
      data: {
        id: idRef.current++,
        createdData,
        emotionId,
        content,
      },
    });
  };

  // 기존 일기 수정
  const onUpdate = (id, createdData, emotionId, content) => {
    dispatch({
      type: "UPDATE",
      data: {
        id,
        createdData,
        emotionId,
        content,
      },
    });
  };

  // 기존 일기 삭제
  const onDelete = (id) => {
    dispatch({
      type: "DELETE",
      id,
    });
  };

  return (
    <>
      <button
        onClick={() => {
          onCreate(new Date().getTime(), 1, "생성된 일기");
        }}
      >
        일기 추가 테스트
      </button>
      <button
        onClick={() => {
          onUpdate(1, new Date().getTime(), 3, "수정된 일기");
        }}
      >
        일기 수정 테스트
      </button>
      <button
        onClick={() => {
          onDelete(1);
        }}
      >
        일기 삭제 테스트
      </button>
      ...생략
    </>
  );
}

export default App;
  • onCreate, onUpdate, onDelete 함수를 생성하고 reducer 안에 action을 자세히 설정해주기
import "./App.css";
...생략

const mockData = [
 ...생략
];

function reducer(state, action) {
  switch (action.type) {
    case "CREATE":
      return [action.data, ...state];
    case "UPDATE":
      return state.map((item) =>
        String(item.id) === String(action.data.id) ? action.data : item
      );
    case "DELETE":
      return state.filter((item) => String(item.id) !== String(action.id));
    default:
      return state;
  }
}

const DiaryStateContext = createContext();
const DiaryDispatchContext = createContext();

function App() {
  const [data, dispatch] = useReducer(reducer, mockData);
  const idRef = useRef(3);

  // 새로운 일기 추가
  const onCreate = (createdData, emotionId, content) => {
	  ...생략
  };

  // 기존 일기 수정
  const onUpdate = (id, createdData, emotionId, content) => {
	  ...생략
  };

  // 기존 일기 삭제
  const onDelete = (id) => {
	  ...생략
  };

  return (
    <>
      ...생략
      <DiaryStateContext.Provider value={data}>
        <DiaryDispatchContext.Provider value={{ onCreate, onUpdate, onDelete }}>
          <Routes>
            <Route path="/" element={<Home />} />
            <Route path="/new" element={<New />} />
            <Route path="/diary/:id" element={<Diary />} />
            <Route path="edit/:id" element={<Edit />} />
            <Route path="*" element={<Notfound />} />
          </Routes>
        </DiaryDispatchContext.Provider>
      </DiaryStateContext.Provider>
    </>
  );
}

export default App;
  • context를 통해서 모든 페이지에서 사용해야 할 state와 함수를 설정해준다.
  • DiaryStateContext
  • DiaryDispatchContext

 

출처 : 한입 크기로 잘라먹는 리액트