Skip to content
Snippets Groups Projects
like-button.tsx 2.08 KiB
Newer Older
Yusuf Akgül's avatar
Yusuf Akgül committed
import { Prisma } from "@prisma/client";
import { useRouter } from "next/navigation";
Yusuf Akgül's avatar
Yusuf Akgül committed
import { startTransition } from "react";
Yusuf Akgül's avatar
Yusuf Akgül committed
import { Icons } from "./icons";
import { Button } from "./ui/button";
Yusuf Akgül's avatar
Yusuf Akgül committed
type likeType = Prisma.LikeUncheckedCreateInput
type postType = Prisma.PostUncheckedCreateInput
type commentType = Prisma.CommentUncheckedCreateInput
//type commentWithLikes = Prisma.CommentGetPayload<typeof commentWithPosts>
export default function LikeButton(props: { data: any }) {
  const likeCount = props.data.Like.length
  /* const likeCount = props.data.likeCount */
  const likeArray = props.data.Like
  /*   const likeCount = countLikes(likeArray, props.data); */





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

    if (postLikeData.postId == undefined) {
      likeData.postId = postLikeData.id!
    } else {
      likeData.postId = postLikeData.postId
      likeData.commentId = postLikeData.id
    }
    likeData.userId = postLikeData.userId
    console.log(likeData.commentId)

    const response = await fetch('http://localhost:3000/api/likes', {
      method: 'PUT',
      body: JSON.stringify(likeData)
    })
Yusuf Akgül's avatar
Yusuf Akgül committed

    startTransition(() => {
      // Refresh the current route and fetch new data from the server without
      // losing client-side browser or React state.
      router.refresh();
    });
    return await response.json()
  }

  return (
    <div>
      <form onSubmit={postLike}>
Yusuf Akgül's avatar
Yusuf Akgül committed
        <Button type="submit" variant="ghost" size="lg" className="float-right" >
Yusuf Akgül's avatar
Yusuf Akgül committed
          <Icons.heart className="h-3 w-3" />
        </Button>
}

function countLikes(likeArray: any, msg: any): number {
  let likeCount = 0;

  if (msg.postId == undefined) {
    likeArray.forEach(function (like: any) {
      if (like.postId == undefined) {
        likeCount++;
      }
    })
  } else {
    likeArray.forEach(function (like: any) {
      if (like.postId != undefined) {
        likeCount++;
      }
    })
  }


  return likeCount;
}