• 카테고리

    질문 & 답변
  • 세부 분야

    풀스택

  • 해결 여부

    미해결

스스로해보기 좋아요, 좋아요 취소 부분 구현

20.08.06 22:06 작성 조회수 1.73k

0

안녕하세요~ 

강의를 듣다보니 시간의 흐름에 따라 바뀐 부분들이 많아서

이번에 나온 개정판 책을 사서 강의와 함께 보면서 개정판 책에 나오는 코드를 기준으로 실습을 하고 있는데

스스로해보기 부분의 좋아요, 좋아요 취소 부분에서 막혔습니다.

main.html에서 좋아요, 좋아요 취소 if 조건 값 설정을 어떻게 해야하는지 궁금합니다.

좋아요 버튼클릭하면 db에 저장까지는 되는데 좋아요 취소로 버튼이 바뀌지 않고 삭제도 되지 않습니다.

{% for twit in twits %}
<div class="twit">
<input type="hidden" value="{{twit.User.id}}" class="twit-user-id">
<input type="hidden" value="{{twit.id}}" class="twit-id">
<div class="twit-author">{{twit.User.nick}}</div>
{% if not followerIdList.includes(twit.User.id) and twit.User.id !== user.id %}
<button class="twit-follow">팔로우하기</button>
{% endif %}
{% if followerIdList.includes(twit.User.id) and twit.User.id !== user.id %}
<button class="twit-unfollow">팔로우끊기</button>
{% endif %}
<div class="twit-content">{{twit.content}}</div>
{% if twit.img %}
<div class="twit-img"><img src="{{twit.img}}" alt="섬네일"></div>
{% endif %}
{% if user and not liker %}
<button class="like">좋아요</button>
{% endif %}
{% if user and liker %}
<button class="unlike">좋아요 취소</button>
{% endif %}
</div>
{% endfor %}
document.querySelectorAll('.like').forEach(function(tag) {
tag.addEventListener('click', function() {
const twitId = tag.parentNode.querySelector('.twit-id').value;
axios.post(`/post/${twitId}/like`)
.then(() => {
location.reload();
})
.catch((err) => {
console.error(err);
});
});
});
document.querySelectorAll('.unlike').forEach(function(tag) {
tag.addEventListener('click', function() {
const twitId = tag.parentNode.querySelector('.twit-id').value;
axios.post(`/post/${twitId}/unlike`)
.then(() => {
location.reload();
})
.catch((err) => {
console.error(err);
});
});
});
router.post('/:id/like', async (req, res, next) => {
try {
const post = await Post.findOne({ where: { id: req.params.id } });
await post.addLiker(req.user.id);
res.send('OK');
} catch (error) {
console.error(error);
next(error);
}
});

router.post('/:id/unlike', async (req, res, next) => {
try {
const post = await Post.findOne({ where: { id: req.params.id } });
await post.removeLiker(req.user.id);
res.send('OK');
} catch (error) {
console.error(error);
next(error);
}
});

답변 8

·

답변을 작성해보세요.

0

윤다빈님의 프로필

윤다빈

2021.05.09

{% if twit.Likers.includes(user.id) %} 이런형태로 하면 좋아요 버튼이 안나오게 되는데 혹시

twit.Liker을 확인해보면 object SequelizeInstance:User 이런 식으로 나오는데

이유를 잘 모르겠습니다.. ㅜ

Likers에는 id만 담겨있어야 합니다. find하실 때 옵션을 잘못주셨을 수 있습니다.

0

네네 아무리해도 안 되시면 다시 질문남겨주세요~

0

박정인님의 프로필

박정인

질문자

2020.08.07

추가적으로 말씀해주신 부분은  되어 있었습니다. 좋아요는 되는데 취소가 안되고 있어서요 스스로 해보기이니 좀 더 찾아보고 고민해보도록 하겠습니다~ 말씀해주셔서 감사합니다~

0

twit.Likers 안에 값이 들어있는지부터 확인하셔야 합니다. twit.Likers도 그냥 생기는 게 아니라 서버쪽에서 post.findAll할 때 include User as Likers 넣어주셔야 Likers가 생깁니다.

0

박정인님의 프로필

박정인

질문자

2020.08.07

그렇게도 해봤었는데 안되서요.... 좋아요 클릭하면 디비에 저장도 잘 되는데 좋아요 취소로 버튼도 안바뀌고 삭제도 안되서 문의드렸어요 다시 한 번 더 코드를 살펴보도록 하겠습니다 ㅠㅠ 

0

{% if twit.Likers.includes(user.id) %}

이렇게 판단해도 될 것 같은데요.

user이나 twits followerIdList는 모두 서버쪽에서 res.render에서 넣어줍니다.

0

박정인님의 프로필

박정인

질문자

2020.08.07

프론트 부분 코드라서 잘 모르겠습니다;;; 조건을 줘야 할 것 같아서 이 것 저것 해보다가 안되서 저렇게 쳐놓기만 한 것이고요.

제로초님이 팔로우 부분 조건 설정하신 것 처럼 하면 되지 않을까 하고 보는데

{% if followerIdList.includes(twit.User.id) and twit.User.id !== user.id %}

위의 코드에서 followerIdList 이 부분이 어디에서 오는지 잘 모르겠습니다.;

0

{% if user and not liker %}

하셨는데 liker가 어디서 온 것인가요? liker에 자신이 이 게시글에 좋아요를 눌렀는지에 대한 정보가 안 담겨있는 것 같습니다.