미라클 메모리

목차

리덕스 환경 구축하기

리덕스 ducks 패턴 환경 구축을 위해서 module이라는 폴더를 생성했고 그 아래에는 memoryReducer을 넣어주었다. 기존에는 App에서 모든 데이터를 불러왔었지만 난 App컴포넌트에서 CRUD 로직을 분리해주고 싶었다. 그렇기에 분리를 하기로 결정했다

스크린샷 2022-03-29 15.38.35.png

Disaptch를 통한 Create

// src/components/template/EditorContainer.js

import { useDispatch } from "react-redux";
import { onCreate } from "../../module/memoryReducer";

const handleSubmit = () => {
	dispatch(onCreate(date, content, emotion));
  };

handleSubmit 이벤트가 발생하는 UI를 클릭할 경우 EditorContainer에 입력한 값들이 disapatch를 통해서 전달되어진다.

onCreate Action

let id = 0;

export const onCreate = (date, content, emotion) => ({
  type: MEMORY_CREATE,
  data: {
    id: id++,
    date: new Date(date).getTime(),
    content,
    emotion,
  },
});

onCreate Action은 type값과 data 객체를 만들어 memoryReducer에 값을 보낸다.

momoryReducer

const memoryReducer = (state = [], action) => {
  let newState = [];
  switch (action.type) {
		...
    case MEMORY_CREATE: {
      newState = [action.data, ...state];
      break;
    }
		...
    default:
      return state;
  }
  localStorage.setItem("memory", JSON.stringify(newState));
  return newState;
};

이때 memoryReducer는 전달받은 Action을 통해서 swtich문을 실행한다. 실행을 통해서 newState라는 빈 배열에 전달한 값들과 기존에 있던 state값을 스프레드 연산자를 통해서 저장해준다.

매개변수 state의 역할