Skip to content
Snippets Groups Projects
following-button.tsx 2.01 KiB
"use client"

import { Follows, Prisma } from '@prisma/client';
import { useSession } from 'next-auth/react';
import { usePathname } from "next/navigation";
import { useEffect, useState } from 'react';
import { Button } from './ui/button';

// 1: Define a type that includes the relation to `Post`
const userWithFollows = Prisma.validator<Prisma.UserArgs>()({
  include: { followers: true, following: true },
})

// 2: Define a type that only contains a subset of the scalar fields
const userPersonalData = Prisma.validator<Prisma.UserArgs>()({
  select: { email: true, name: true },
})

// 3: This type will include a user and all their posts
type UserWithFollows = Prisma.UserGetPayload<typeof userWithFollows>


export default function FollowButton({ user, followingId }: { user: UserWithFollows; followingId: string }) {
  const [isFollowing, setIsFollowing] = useState(false);
  const [follows, setFollows] = useState([]);
  const [buttonPressed, setButtonPress] = useState(false);

  const pathname = usePathname()
  const { data: session } = useSession();

  async function fetchFollows() {

    try {
      const response = await fetch('/api/followers')

      const data = await response.json()
      setFollows(data.follows)
      setIsFollowing(false)
      data.follows?.forEach((f: Follows) => {

        if (f.followerId == user.id && f.followingId == followingId) {
          setIsFollowing(true)
          return;
        }
      })
    } catch (error) {

    }
  }
  useEffect(() => {
    fetchFollows()
    // TODO: fix this warning
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [buttonPressed])

  async function handleFollow(e: any) {
    e.preventDefault()

    const response = await fetch('/api/followers', {
      method: 'PUT',
      body: JSON.stringify({ user, followingId })
    })

    setButtonPress(!buttonPressed)
  }

  return (
    <>
      {pathname !== `/${session?.user.username}` &&
        <Button onClick={handleFollow}>
          {isFollowing ? 'Unfollow' : 'Follow'}
        </Button>}
    </>
  );
}