Skip to content

Conversation

@leetaesk
Copy link

✏️ 작업 내용

#️⃣ 연관된 이슈

#50


📷 작업 결과

작업 결과 사진을 업로드해주세요.

week9-mission.mp4

💡 함께 공유하고 싶은 부분

해당 주차를 공부하면서 함께 이야기하고 싶은 주제를 남겨주세요.

(어려웠던 부분과 해결 과정, 핵심 코드, 참고한 자료 등)


모달을 슬라이스로 관리하는 부분에서 이슈가 좀 있었는데 노션에 정리해놨습니다. 해결 가능하다면 내일 스터디전까지 해갈게요

🤔 질문

해당 주차 워크북을 공부하면서 궁금했던 질문들을 남겨주세요.


✅ 워크북 체크리스트

  • 모든 핵심 키워드 정리를 마쳤나요?
  • 핵심 키워드에 대해 완벽히 이해하였나요?
  • 실습/미션을 수행하였나요?

✅ 컨벤션 체크리스트

  • pr 제목을 컨벤션에 맞게 작성하였나요?
  • pr에 해당되는 이슈를 연결하였나요?
  • 적절한 라벨을 설정하였나요?
  • 코드리뷰를 요청하기 위해 reviewer를 등록하였나요?
  • 닉네임/main 브랜치의 최신 상태를 반영하고 있나요?

@leetaesk leetaesk self-assigned this May 29, 2025
@leetaesk leetaesk added the 💡 Mission 미션 수행 label May 29, 2025
Comment on lines +23 to +25
{cartItems.map((item) => (
<CartItem item={item} />
))}
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

CartItem 컴포넌트에 key 필요합니다!

Comment on lines +39 to +40
state.onConfirm = action.payload.onConfirm;
state.onCancel = action.payload.onCancel;
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

노션에 이슈 확인했어요.
모달에 연결되야 하는 핸들러는 상태 말고
Middleware를 활용해 openModal, closeModal action에 연결해 두는 건 어떨까요??
제가 해 본 코드 공유드립니다!

import { PayloadAction, createSlice } from '@reduxjs/toolkit';
import { Middleware } from '@reduxjs/toolkit';

interface ModalState {
  isOpen: boolean;
  message: string;
  confirmText?: string;
  cancelText?: string;
  modalType: string; // 모달 타입 식별
}

const initialState: ModalState = {
  isOpen: false,
  message: '',
  confirmText: '예',
  cancelText: '아니오',
  modalType: '',
};

const modalSlice = createSlice({
  name: 'modal',
  initialState,
  reducers: {
    openModal: (
      state,
      action: PayloadAction<{
        message: string;
        confirmText?: string;
        cancelText?: string;
        modalType: string;
      }>,
    ) => {
      // 열기
      state.isOpen = true;
      // 모달설정
      state.message = action.payload.message;
      state.confirmText = action.payload.confirmText ?? '예';
      state.cancelText = action.payload.cancelText ?? '아니오';
      state.modalType = action.payload.modalType;
    },
    closeModal: (state) => {
      // 닫기
      state.isOpen = false;
    },
  },
});

// 모달에 핸들러 추가
const modalHandlers = new Map<
  string,
  { onConfirm?: () => void; onCancel?: () => void }
>();

export const registerModalHandler = (
  type: string,
  handlers: { onConfirm?: () => void; onCancel?: () => void },
) => {
  modalHandlers.set(type, handlers);
};

export const getModalHandler = (type: string) => {
  return modalHandlers.get(type);
};

export const modalMiddleware: Middleware =
  (store) => (next) => (action) => {
    if ((action as PayloadAction).type === 'modal/openModal') {
      const handler = modalHandlers.get(store.getState().modal.modalType);
      handler?.onConfirm?.();
    }
    if ((action as PayloadAction).type === 'modal/closeModal') {
      const handler = modalHandlers.get(store.getState().modal.modalType);
      handler?.onCancel?.();
    }
    return next(action);
  };

export const { openModal, closeModal } = modalSlice.actions;
export default modalSlice.reducer;

그리고 모달 컴포넌트에서

export default function Modal() {
  const dispatch = useAppDispatch();
  const { isOpen, message, modalType } = useAppSelector((state) => state.modal);
  // 핸들러 가져오기
  const handler = modalType ? getModalHandler(modalType) : null;

  if (!isOpen) return null;

  const handleConfirm = () => {
    handler?.onConfirm?.();
  };

  const handleCancel = () => {
    if (handler?.onCancel) handler.onCancel();
    else dispatch(closeModal());
  };
  // ...
}

모달 사용할 때는

function CardCover({ cart }: CardCoverProps) {
  // ...
  // 모달에 핸들러 연결해두기
  registerModalHandler('navigatrCartConfirm', {
    onConfirm: () => {
      dispatch(closeModal());
      navigate(ROUTES.CART);
    },
  });

  const handleClick = () => {
    dispatch(addItem(cart));
    dispatch(
      openModal({
        modalType: 'navigatrCartConfirm',
        message: '장바구니로 이동하시겠습니까?',
      }),
    );
  };

  // ...
}

@leetaesk leetaesk merged commit 9a9a12c into jackson/main Jun 19, 2025
1 check passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

💡 Mission 미션 수행

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants