목차

스크린샷 2022-03-16 08.06.53.png

GalleryContainer의 Alert & Modal

GalleryContainer는 데이터가 바인딩이 이루어지는 컨테이너 컴포넌트이다. 컨테이너 컴포넌트에서는 Alert와 Modal에 대한 로직이 들어가 있다.

// src/components/profile/GalleryContainer/index.jsx

const isPostAlert = postId => {
    setPostAlert(!postAlert);
    if (typeof postId === "string") {
      dispatch(deletePost(postId));
    }
  };
// src/components/profile/GalleryContainer/index.jsx
	<>
	<Modal visible={postDialog}>
		<ModalAlertBtn isAlert={isPostAlert}>삭제</ModalAlertBtn>
		<ModalListBtn isDialog={isPostDialog}>수정</ModalListBtn>
		<ModalListBtn isDialog={isPostDialog}>닫기</ModalListBtn>
	</Modal>
	<Alert visible={postAlert} messageText="게시글을 삭제할까요?">
		<AlertBtn isAlert={isPostAlert}>취소</AlertBtn>
		<AlertBtn isAlert={() => isPostAlert(postId && postId)}>
			삭제
		</AlertBtn>
	</Alert>
	</>

isPostAlert 라는 함수가 호출이되면 postAlert의 Boolean 값이 바뀜에 따라서 컴포넌트가 보여줄지 안보여줄지를 결정한다 그 과정에서 애니메이션이 추가되어있다.

Alert & Modal 컨트롤러 함수 Props로 전달하기

// src/components/profile/GalleryContainer/index.jsx

<PostCard postDialog={isPostDialog} ...../>

PostCard 라는 컴포넌트에는 postDialog라는 props명으로 isPostDialog라는 함수 컨트롤러를 보낸다. PostCard는 해당 컨트롤러를 props를 통해서 상속받아 사용한다.

// src/components/common/PostCard/index.jsx

<CardMoreBtn onClick={() => postDialog(postid)} />

그리고 CardMoreBtn에 onClick이라는 이벤트를 주어 해당 게시물에 대한 postId값을 함께 인수로 전달한다.

// src/components/profile/GalleryContainer/index.jsx

const isPostAlert = postId => {
    setPostAlert(!postAlert);
    if (typeof postId === "string") {
      dispatch(deletePost(postId));
    }
  };

isPostAlert를 통해서 해당 ID값이 전달이 된다. 또한 postID가 “string” 이 맞냐는 조건문을 한번 거치고 난 후에 dispatch를 통해서 해당 게시물에 대한 아이디 값을 deletePost라는 함수를 통해서 전달한다

deletePost Action

// src/actions/postActions.js

export const deletePost = postId => async (dispatch, getState) => {
  try {
    dispatch({
      type: POST_DELETE_REQUEST,
    });

    const {
      userLogin: { userInfo },
    } = getState();

    const config = {
      headers: {
        Authorization: `Bearer ${userInfo.user.token}`,
      },
    };
    const { data } = await axios.delete(`${API_URL}/post/${postId}`, config);
    dispatch({
      type: POST_DELETE_SUCCESS,
      payload: data,
    });

    document.location.href = "/profile";
  } catch (error) {
 ....
  }
};

deletePost는 클릭이벤트가 발생한 게시물의 postId를 전달받는다.

    dispatch({
      type: POST_DELETE_REQUEST,
    });