Untitled

mail@pastecode.io avatar
unknown
plain_text
a year ago
2.3 kB
1
Indexable
Never
```import React, { useState, useEffect } from 'react';
import './LikeButton.css'
import { likePost, dislikePost } from '../../services/post.service';
import { get, ref } from 'firebase/database';
import { database } from '../../config/firebase-config';
import ThumbUpOffAltIcon from '@mui/icons-material/ThumbUpOffAlt';
import ThumbUpIcon from '@mui/icons-material/ThumbUp';
import { useNavigate } from 'react-router-dom';
import { auth } from '../../config/firebase-config';
import { getUserDataFromRealtimeDatabase } from '../../services/auth.service';

function LikeButton({ postId }) {
  const [liked, setLiked] = useState(false);
  const [likesCounter, setLikesCounter] = useState(0);
  const navigate = useNavigate();
  const currUser = auth.currentUser;
  const [userData, setUserData] = useState(null);

  useEffect(() => {
    const fetchUserData = async () => {
      const user = await getUserDataFromRealtimeDatabase();
     
      if (user.length > 0) {
        setUserData(user[0]);
        console.log(userData);
        // Fetch the number of likes for the post from Firebase
        const postRef = ref(database, `posts/${postId}/likedBy`);
        get(postRef).then((snapshot) => {
          const likes = snapshot.exists() ? Object.keys(snapshot.val()).length : 0;
          setLikesCounter(likes);
        });

        // Check if the current user has liked the post
        const userRef = ref(database, `posts/${postId}/likedBy/${userData.username}`);
        get(userRef).then((snapshot) => {
          if (snapshot.exists()) {
            setLiked(true);
          }
        });
      }
    };

    fetchUserData();
  }, [postId]);

  const handleLikeClick = () => {
    if (currUser !== null) {
      if (liked) {
        dislikePost(userData.username, postId);
        setLikesCounter((remLike) => remLike - 1);
      } else {
        likePost(userData.username, postId);
        setLikesCounter((addLike) => addLike + 1);
      }
      setLiked(!liked);
    } else {
      navigate('/log-in');
    }
  };

  return (
    <div>
      <button onClick={handleLikeClick} style={{ color: '#04A9FF' }}>
        {liked ? <ThumbUpIcon /> : <ThumbUpOffAltIcon />}
      </button>
      <span>  {likesCounter}</span>
    </div>
  );
}

export default LikeButton;
```