작성
·
153
0
안녕하세요! 요즘 복습 겸 혼자 만들어보며 댓글 삭제 기능을 추가로 만들어 보는 중입니다
댓글 작성할 때는 게시글의 id 값을 가져와서 그 게시글에 추가를 하지만 댓글삭제는 댓글 id만 있으면 바로 삭제가 되지 않을까 하는 생각으로 작성했습니다.
현재 각 댓글 별 삭제 버튼을 누르면 삭제 api가 잘 작동하나, 바로 프론트 측에서 렌더 되지 않고 새로고침을 해야 댓글이 사라집니다.
삭제버튼 클릭 시 바로 삭제가 되도록 할 수 있을까요?
제가 찾아보는데 오타인건지 잘 보이지 않네요 ㅠㅠ
댓글 목록과 댓글 삭제 버튼
<List
dataSource={post.Comments}
renderItem={(item) =>(
<Comment
avatar={(
<Link href={`user/${item.User.id}`}>
<a><Avatar size="small">{item.User.nickname[0]}</Avatar></a>
</Link>
)}
author={(
<Link href={`user/${item.User.id}`}>
<a><b>{item.User.nickname}</b></a>
</Link>
)}
content={(
<p>
{item.content}
<TimeStamp>{dayjs(item.createdAt).locale('ko').fromNow()}</TimeStamp>
</p>
)}
>
{userId && item.User.id === userId
? (<DeleteComment type="text" onClick={onDeleteComment(item.id)}><DeleteOutlined /></DeleteComment>)
: null
}
</Comment>
)}
/>
댓글 삭제(onDeleteComment())
const onDeleteComment = (id) => () => {
dispatch({
type: REMOVE_COMMENT_REQUEST,
data: id,
})
};
리듀서
case REMOVE_COMMENT_REQUEST:
draft.removeCommentLoading = true;
draft.removeCommentDone = false;
draft.removeCommentError = null;
break;
case REMOVE_COMMENT_SUCCESS:
draft.removeCommentLoading = false;
draft.removeCommentDone = true;
draft.mainPosts = draft.mainPosts.filter((v) => v.id !== action.data.CommentId);
break;
case REMOVE_COMMENT_FAILURE:
draft.removeCommentLoading = false;
draft.removeCommentError = action.error;
break;
사가
function removeCommentAPI(data) {
return axios.delete(`/post/comment/${data}`); // DELETE /post/comment/1
}
function* removeComment(action) {
try {
const result = yield call(removeCommentAPI, action.data);
yield put({
type: REMOVE_COMMENT_SUCCESS,
data: result.data, //성공결과
});
} catch (err) {
console.error(err);
yield put({
type: REMOVE_COMMENT_FAILURE,
error: err.response.data, //실패 결과
})
}
}
라우터
// 댓글 삭제
router.delete('/comment/:commentId', isLoggedIn, async (req, res, next) => { //DELETE /post/comment/1
try {
const comment = await Comment.findOne({
where: { id: req.params.commentId },
});
if (!comment) {
res.status(403).send('존재하지 않는 댓글입니다.');
}
await comment.destroy({ id: req.params.commentId });
res.status(200).json({ CommentId: parseInt(req.params.commentId, 10) });
} catch (error) {
console.error(error);
next(error)
}
});