댓글삭제 기능도 해보고싶어서 사가 리듀서 백라우트 프론트 코드 작성해봤어요~
401Unauthorized 에러뜨는데 어떤 부분을 고쳐야 할까요?
// 댓글삭제하기
const onRemoveComments = useCallback(userId => () => {
alert('댓글을 삭제하시겠습니까?');
dispatch({
type: REMOVE_COMMENT_REQUEST,
data: userId,
});
});
< post.js/reducers >
// 댓글 지우기
case REMOVE_COMMENT_REQUEST: {
return {
...state,
};
}
case REMOVE_COMMENT_SUCCESS: {
const postIndex = state.mainPosts.findIndex(v => v.id === action.data.postId);
const post = state.mainPosts[postIndex];
const Comments = post.Comments.filter(v => v.id !== action.data.comments );
const mainPosts = [...state.mainPosts];
mainPosts[postIndex] = { ...post, Comments };
return {
...state,
mainPosts,
};
}
case REMOVE_COMMENT_FAILURE: {
return {
...state,
};
}
< post.js/sagas >
// 댓글 지우기
function removeCommentsAPI(postId) {
return axios.delete(`/post/${postId}/comment`);
}
function* removeComments(action) {
try {
const result = yield call(removeCommentsAPI, action.data);
yield put({
type: REMOVE_COMMENT_SUCCESS,
data: {
postId: action.data,
comments: result.data,
},
});
} catch (e) {
console.error(e);
yield put({
type: REMOVE_COMMENT_FAILURE,
error: e,
});
}
}
-백
<post.js/routes>
// 댓글삭제하기 routes
router.delete('/:id/comment', isLoggedIn, async (req, res, next) => {
try {
const comment = await db.Comment.findOne({ where: { id: req.params.id } });
if (!comment) {
return res.status(404).send('댓글이 존재하지 않습니다.');
}
await db.Comment.destroy({ where: { id: req.params.id } });
res.send(req.params.id);
} catch (e) {
console.error(e);
next(e);
}
});