Immer 적용하기

준호·2020년 8월 31일
0
Immer 적용 준비

npm i immer

import produce from 'immer' // reduce에 달아준다.

Immer 적용 전 코드
switch (action.type) { 
case ADD_POST_REQUEST:
        return {
          ...state,
          addPostLoading: true,
          addPostDone: false,
          addPostError: null,
        };
      case ADD_POST_SUCCESS:
        return {
          ...state,
          addPostLoading: false,
          addPostDone: true,
          mainPosts: [dummyData(action.data), ...state.mainPosts],
        };
      case ADD_POST_FAILURE:
        return {
          ...state,
          addPostLoading: false,
          addPostError: action.error,
        };
}

case ADD_COMMENT_SUCCESS: {
      const postIndex = state.mainPosts.findIndex((y) => y.id === action.data.postId);
      const post = { ...state.mainPosts[postIndex] };
      post.Comments = [dummyComment(action.data.content), ...post.Comments];
      const mainPosts = [...state.mainPosts];
      mainPosts[postIndex] = post;
    return {
      mainPosts,
      addCommentLoading: false,
      addCommentDone : true,
      break;
    }
  }
default:
	return state;
Immer 적용 된 코드
produce(state, (draft) => {
  switch (action.type) {
    case ADD_POST_REQUEST:
      draft.addPostLoading = true;
      draft.addPostDone = false;
      draft.addPostError = null;
      break;
    case ADD_POST_SUCCESS:
      draft.addPostLoading = false;
      draft.addPostDone = true;
      draft.mainPosts.unshift(dummyData(action.data));
      break;
    case ADD_POST_FAILURE:
      draft.addPostLoading = action.error;
      draft.addPostError = false;
      break;
      }
  }
        
case ADD_COMMENT_SUCCESS: {
      const post = draft.mainPosts.find((v) => v.id === action.data.postId);
      post.Comments.unshift(dummyComment(action.data.content));
      draft.addCommentLoading = false;
      draft.addCommentDone = true;
      break;
    }        
default:
	break;

no-param-reaaign.eslintrc에 추가하기

이전보다 10줄가량 줄어든게 보인다.

return문을 안쓰고 break를 쓰는 점, 앞에 draft를 붙이는 점, 불변성을 지키지 않는 점이 눈에 띈다.
불변성을 지키는 데 있어 해가 될 수 있는 unshiftpush같은것을 마음껏 쓸 수 있다.
마지막 default문return state가 아닌 break를 쓴다.

immer를 사용 할 때는 불변성을 꼭 지키지 말아야 한다

profile
빠르게 발전중인 프론트엔드 개발자

0개의 댓글