File size: 1,223 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
import { useState } from 'react';
import { useDispatch } from 'react-redux';
import { useAuth } from '../context/auth';
import { updatePostReaction } from '../lib/api';
import { setLoginAlert } from '../store/loginAlert';

const useClickReactToPost = (reactionArr, postId, reactType) => {
   const user = useAuth();
   const dispatch = useDispatch();
   const [updatingReact, setUpdatingReact] = useState(false);

   const clickReactHandler = () => {
      if (!user?.userId) {
         dispatch(setLoginAlert(true));
         return;
      }

      setUpdatingReact(true);

      const prevReactionArr = reactionArr || [];
      const userId = user.userId;

      const transformedReact = prevReactionArr.includes(userId)
         ? prevReactionArr.filter((id) => id !== userId)
         : [...prevReactionArr, userId];

      updatePostReaction({ [reactType]: transformedReact }, postId)
         .then((_) => {
            setUpdatingReact(false);

            // console.log('react added successfully');
         })
         .catch((err) => {
            setUpdatingReact(false);

            console.log(err);
         });
   };

   return { clickReactHandler, updatingReact };
};

export default useClickReactToPost;