지난번에 '좋아요' 기능을 구현하는 데까지 성공했다.
그런데, 지금 와서 생각해보니까 '좋아요' 취소는 구현을 안 했다.. 🥲
그래서 다른 팀원이 눈치채기 전에 부랴부랴 추가 중이다.
<FavoriteIcon className={styles.icon} onClick={handleoCancelLike}/>
const handleoCancelLike = async () => {
try {
const response = await axios.post('/api/postlike/cancel', {
userId: userId,
postId: postId
});
console.log(response.data);
setIsLiked(false); // 좋아요 상태를 false로 설정
} catch (error) {
console.error('Error unliking the post:', error);
}
};
// controller
Mapping("/cancel")
public ResponseEntity<String> cancleLikePost(@RequestBody PostLikeDTO dto) {
boolean isCancled = postLikeService.cancleLikePost(dto.getUserId(), dto.getPostId());
if (isCancled) {
return ResponseEntity.ok("Post unliked successfully");
} else {
return ResponseEntity.badRequest().body("Failed to unlike post");
}
}
// service
public boolean cancleLikePost(String userId, Integer postId) {
try {
// 1. userId와 postId로 PostLikeEntity를 찾기
PostLikeEntity postLike = postLikeRepository.findByUserIdAndPostId(userId, postId);
if (postLike != null) {
// 2. 찾은 엔티티를 삭제
postLikeRepository.delete(postLike);
return true;
}
return false; // 좋아요가 존재하지 않는 경우
} catch (Exception e) {
return false;
}
}
// repostiory
PostLikeEntity findByUserIdAndPostId(String userId, Integer postId);
데이터가 정상적으로 삭제되는 것을 확인할 수 있다.