File size: 2,121 Bytes
f5071ca
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
import { useState } from 'react';
import { useDispatch } from 'react-redux';
import { updateComment } from '../lib/api';
import { setCurrentComments } from '../store/comment/currentComments';
import { setLoginAlert } from '../store/loginAlert';

const useClickLikeToComment = (currentUserId, postId) => {
   const dispatch = useDispatch();

   const [updatingLike, setUpdatingLike] = useState(false);

   const handleClickLike = (comments, commentId) => {
      // when click like multiple comment item quickly, previous comment array is not update yet
      // so I put previous trnasformed comment arr to redux store and use them in the next time

      if (!currentUserId) {
         dispatch(setLoginAlert(true));
         return;
      }

      setUpdatingLike(true);

      const externalComments = comments.map((comment) =>
         comment.commentId === commentId
            ? {
                 ...comment,
                 likes: comment.likes.includes(currentUserId)
                    ? comment.likes.filter((id) => id !== currentUserId)
                    : [...comment.likes, currentUserId],
              }
            : comment
      );

      const modifiedComments = externalComments.map((comment) => ({
         ...comment,
         replies: {
            ...Object.values(comment.replies).map((cmt) =>
               cmt.commentId === commentId
                  ? {
                       ...cmt,
                       likes: cmt.likes.includes(currentUserId)
                          ? cmt.likes.filter((id) => id !== currentUserId)
                          : [...cmt.likes, currentUserId],
                    }
                  : cmt
            ),
         },
      }));

      dispatch(setCurrentComments(modifiedComments));

      updateComment(modifiedComments, postId)
         .then((_) => {
            setUpdatingLike(false);
            // console.log('updated like');
         })
         .catch((err) => {
            setUpdatingLike(false);
            console.log(err);
         });
   };

   return { handleClickLike, updatingLike };
};

export default useClickLikeToComment;