Skip to content
Snippets Groups Projects
following-button.tsx 1.24 KiB
import { PrismaClient } from '@prisma/client';
import { useState } from 'react';
import { Button } from './ui/button';

const prisma = new PrismaClient();

async function getFollower(userId: number, followerId: number) {
  const follower = await prisma.follows.findFirst({
    where: {
      followerId: followerId,
      followingId: userId,
    },
  });

  return follower;
}

export default function FollowButton({ userId, followerId }: { userId: number; followerId: number }) {
  const [isFollowing, setIsFollowing] = useState(false);

  const handleFollow = async () => {
    const follower = await getFollower(userId, followerId);

    if (follower) {
      // User is already following, so unfollow
      await prisma.follows.delete({
        where: {
          followerId_followingId: {
            followerId: followerId,
            followingId: userId,
          },
        },
      });
      setIsFollowing(false);
    } else {
      // User is not following, so follow
      await prisma.follows.create({
        data: {
          followerId: followerId,
          followingId: userId,
        },
      });
      setIsFollowing(true);
    }
  };

  return (
    <Button onClick={handleFollow}>
      {isFollowing ? 'Unfollow' : 'Follow'}
    </Button>
  );
}