📝 배경
- 본 프로젝트 (삐삐:Best Interior)에서는 인테리어 관련 게시글, 팁관련 게시글을 작성할 수 있으며, 사용자는 댓글과 답글을 작성 할 수 있도록 기획하였다.
- 여기서 댓글은, 말그대로 게시글의 댓글, 답글은 댓글의 댓글이다.
🚨 문제 상황 - (1). 새로 작성한 댓글의 답글이 작성이 안되는 버그
- 새로운 댓글을 작성할 경우, 답글작성이 안되는 오류가 발생하였다.
- 오류: TypeError: Cannot read property 'push' of undefined
- 하지만, 새로고침을 할경우에는 정상적으로 답글이 작성되는 현상임을 확인하였음
🔍️ 원인 파악
- 에러 메세지에서 확인이 가능하듯이, 배열이 아닌 undefined에 push를 하려고 해서 발생하는 오류임을 파악
// 수정 전 코드
const postReply = async (feedReplyId) => {
const configParams = {
method: "POST",
url: `/feed/${feedId}/feedReply/${feedReplyId}/feedComment`,
headers: {
"ngrok-skip-browser-warning": "69420",
},
data: {
content: inputReply,
},
};
try {
const res = await api(configParams);
if (res && res.status === 200) {
const newReply = res.data;
// 답글 배열에 새 답글 추가
const updatedComments = [...comments, newReply];
setEnterReply(updatedComments);
// 상위 컴포넌트에서 넘어온 comment를 기반으로 업데이트
const updatedFeedData = JSON.parse(JSON.stringify(feedData));
updatedFeedData.replies.forEach((reply) => {
if (reply.feedReplyId === commentId) {
reply.comments.push(newReply);
}
});
setFeedData(updatedFeedData);
setInputReply("");
toast.success("답글을 입력하셨습니다.");
}
} catch (err) {
toast.error("답글을 추가할 수 없습니다.");
}
};
- 또한, 새로고침을 할경우 답글기능이 정상작동되는것으로 보아 새로고침을 통해 get요청으로 받아오는 답글 데이터를 살펴보았음.
// 서버에서 수신되는 답글, 댓글 데이터 일부
replies": [ {
repliyId:1
content: 댓글1
comments: [ ]
},
{
repliyId:2
content: 댓글2
comments: [ { commentId:1, content: 답글1 },{ commentId:2, content: 답글12 } ],
},
],
- 이런식으로, 빈 답글일 경우 빈배열로 데이터를 전송해주는 것을 확인 할 수 있었음
- 즉, 원인은 새로운 댓글을 작성할때, 댓글의 프로퍼티 comments의 값을 따로 설정해 주지 않아서, undefined 오류가 뜨는 것이였다..
- 당연히 undefined에 push를 할 수 없기 때문에 발생한 오류였던것이다.
🔨 해결 방안
- 댓글의 프로퍼티로 comments의 값을 [] 빈배열로 설정을 해줘야 한다는 것을 깨달을 수 있었다.
// 수정한 코드
const postReply = async (feedReplyId) => {
const configParams = {
method: "POST",
url: `/feed/${feedId}/feedReply/${feedReplyId}/feedComment`,
headers: {
"ngrok-skip-browser-warning": "69420",
},
data: {
content: inputReply,
},
};
try {
const res = await api(configParams);
if (res && res.status === 200) {
const newReply = res.data;
// 기존 feedData를 얕은 복사하여 업데이트 진행
const updatedFeedData = { ...feedData };
updatedFeedData.replies = updatedFeedData.replies.map((reply) => {
if (reply.feedReplyId === commentId) {
// 해당 답글의 comments 배열에 새로운 답글 추가
// reply.comments가 undefined일 경우 기본적으로 빈 배열로 설정해야함!!
const updatedComments = Array.isArray(reply.comments)
? [...reply.comments]
: [];
return {
...reply,
comments: [...updatedComments, newReply],
};
}
return reply;
});
// 업데이트된 feedData를 설정
setFeedData(updatedFeedData);
setInputReply("");
toast.success("답글을 입력하셨습니다.");
} else {
console.error("POST 요청 실패: " + res.status);
toast.error("답글을 추가할 수 없습니다.");
}
} catch (err) {
console.error("예외 발생: " + err);
toast.error("답글을 추가하는 중 오류가 발생했습니다.");
}
};
🎉 결과
🌱 느낀점
- 리액트의 상태값을 조작하거나 가공할때 항상 예외케이스 혹은 사이드 이펙트까지 고려해서 코드를 짜도록 노력해야겠다!
'Project > 삐삐(BIBI: Best Interior)' 카테고리의 다른 글
[최적화] Pagenation 구현, 정적리소스 서버 구축 (0) | 2023.10.05 |
---|---|
[JWT] 토큰 인가 및 토큰 재발급 관련 트러블슈팅 (0) | 2023.09.18 |
[AWS S3] 클라이언트 배포 시 404 에러 (0) | 2023.09.17 |