From 26c4e7e52c306b0e95f33febc4b6921b528c912b Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Yusuf=20Akg=C3=BCl?= <s86116@bht-berlin.de>
Date: Sat, 8 Jul 2023 15:33:12 +0200
Subject: [PATCH] small fix and working follow button

---
 .../(user)/[username]/(profile)/layout.tsx    |  4 +-
 app/api/users/follow/route.ts                 |  4 +-
 components/follow-button.tsx                  | 51 +++++++++++++++----
 components/profile/api/follow-user.ts         |  7 +--
 components/profile/api/unfollow-user.ts       |  9 ++--
 .../profile/components/profile-navbar.tsx     |  8 +--
 6 files changed, 53 insertions(+), 30 deletions(-)

diff --git a/app/(content)/(user)/[username]/(profile)/layout.tsx b/app/(content)/(user)/[username]/(profile)/layout.tsx
index 2b95743..f79ac51 100644
--- a/app/(content)/(user)/[username]/(profile)/layout.tsx
+++ b/app/(content)/(user)/[username]/(profile)/layout.tsx
@@ -6,8 +6,8 @@ import { Card } from "@/components/ui/card"
 import { UserNotFound } from "@/components/user-not-found"
 import getURL from "@/lib/utils"
 
-export const dynamic = 'force-dynamic'
-export const fetchCache = 'force-no-store'
+// export const dynamic = 'force-dynamic'
+// export const fetchCache = 'force-no-store'
 
 export default async function ProfileLayout({
     params,
diff --git a/app/api/users/follow/route.ts b/app/api/users/follow/route.ts
index 3c6dc93..7e36eb5 100644
--- a/app/api/users/follow/route.ts
+++ b/app/api/users/follow/route.ts
@@ -87,9 +87,7 @@ export async function PUT(request: Request) {
 // unfollow a user
 export async function DELETE(request: Request) {
     const session = await getCurrentUser()
-    const { searchParams } = new URL(request.url)
-
-    const userId = searchParams.get("userId") || undefined
+    const { userId } = await request.json()
 
     const followerIdSchema = z
         .object({
diff --git a/components/follow-button.tsx b/components/follow-button.tsx
index 552c4e9..294bf27 100644
--- a/components/follow-button.tsx
+++ b/components/follow-button.tsx
@@ -1,5 +1,8 @@
 "use client"
 
+import { useRouter } from "next/navigation"
+import { useEffect, useState } from "react"
+import { Icons } from "./icons"
 import { useFollow } from "./profile/hooks/use-follow"
 import { Button } from "./ui/button"
 import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle, DialogTrigger } from "./ui/dialog"
@@ -16,17 +19,41 @@ export const FollowButton = ({
     const followMutation = useFollow("follow")
     const unfollowMutation = useFollow("unfollow")
 
+    const [text, setText] = useState<"Following" | "Unfollow">("Following")
+    const [isHovered, setIsHovered] = useState(false)
+    const [open, setOpen] = useState(false)
+
+    const router = useRouter()
+
+    useEffect(() => {
+        if (followMutation.isSuccess) {
+            router.refresh()
+        }
+        if (unfollowMutation.isSuccess) {
+            setOpen(false)
+            router.refresh()
+        }
+    }, [router, followMutation.isSuccess, unfollowMutation.isSuccess])
+
     return (
-        <Dialog>
+        <Dialog open={open} onOpenChange={setOpen}>
             {isFollowing ? (
-                <Button variant="outline" size="lg" >
-                    <span className="hover:hidden">Following</span>
-                    <DialogTrigger>
-                        <span className="hidden hover:block text-destructive border-destructive">Unfollow</span>
-                    </DialogTrigger>
-                </Button>
+                <DialogTrigger asChild>
+                    <Button variant={`${isHovered ? "destructive" : "outline"}`} size="lg"
+                        className="w-24"
+                        onMouseEnter={() => {
+                            setText("Unfollow")
+                            setIsHovered(true)
+                        }}
+                        onMouseOut={() => {
+                            setText("Following")
+                            setIsHovered(false)
+                        }}>
+                        {text}
+                    </Button>
+                </DialogTrigger>
             ) : (
-                <Button variant="outline" size="lg" onClick={() => followMutation.mutate({ userId })}>
+                <Button size="lg" onClick={() => followMutation.mutate({ userId })}>
                     Follow
                 </Button>
             )}
@@ -34,12 +61,14 @@ export const FollowButton = ({
                 <DialogHeader>
                     <DialogTitle>Unfollow @{username}?</DialogTitle>
                     <DialogDescription>
-                        Their Gweets will no longer show up in your home timeline.
-                        You can still view their profile, unless their Tweets are protected.
+                        You can still view their profile, unless their Gweets are protected.
                     </DialogDescription>
                 </DialogHeader>
                 <DialogFooter>
-                    <Button type="submit" onClick={() => unfollowMutation.mutate({ userId })}>
+                    <Button type="submit" onClick={() => unfollowMutation.mutate({ userId })} disabled={unfollowMutation.isLoading}>
+                        {unfollowMutation.isLoading && (
+                            <Icons.spinner className="mr-2 h-4 w-4 animate-spin" />
+                        )}
                         Unfollow
                     </Button>
                 </DialogFooter>
diff --git a/components/profile/api/follow-user.ts b/components/profile/api/follow-user.ts
index b7d8c95..bfa5bf2 100644
--- a/components/profile/api/follow-user.ts
+++ b/components/profile/api/follow-user.ts
@@ -1,11 +1,8 @@
 export const followUser = async (userId: string) => {
-    console.log({ userId })
     try {
         const data = await fetch("/api/users/follow", {
-            method: "POST",
-            body: JSON.stringify({
-                userId,
-            }),
+            method: "PUT",
+            body: JSON.stringify({ userId }),
         }).then((result) => result.json())
 
         return data
diff --git a/components/profile/api/unfollow-user.ts b/components/profile/api/unfollow-user.ts
index fc8d3da..1d23d10 100644
--- a/components/profile/api/unfollow-user.ts
+++ b/components/profile/api/unfollow-user.ts
@@ -1,9 +1,8 @@
-export const unfollowUser = async (
-    user_id: string,
-) => {
+export const unfollowUser = async (userId: string) => {
     try {
-        const { data } = await fetch(`/api/users/follow?user_id=${user_id}`, {
-            method: "DELETE"
+        const data = await fetch(`/api/users/follow`, {
+            method: "DELETE",
+            body: JSON.stringify({ userId }),
         }).then((result) => result.json())
 
         return data
diff --git a/components/profile/components/profile-navbar.tsx b/components/profile/components/profile-navbar.tsx
index 774b4e1..94a436a 100644
--- a/components/profile/components/profile-navbar.tsx
+++ b/components/profile/components/profile-navbar.tsx
@@ -10,25 +10,25 @@ export const ProfileNavbar = ({ children, param }: { children: React.ReactNode,
     return (
         <Tabs defaultValue={"gweets"} value={pathValue} className="w-full h-full p-6 md:p-12 ">
             <TabsList className="grid w-full grid-cols-4">
-                <Link href={`/${param}`} className="w-full inline-flex items-center justify-center">
+                <Link href={`/${param}`} scroll={false} className="w-full inline-flex items-center justify-center">
                     <TabsTrigger value="gweets" className="w-full">
                         Gweets
                     </TabsTrigger>
                 </Link>
 
-                <Link href={`/${param}/games`} className="w-full inline-flex items-center justify-center">
+                <Link href={`/${param}/games`} scroll={false} className="w-full inline-flex items-center justify-center">
                     <TabsTrigger value="games" className="w-full">
                         Games
                     </TabsTrigger>
                 </Link>
 
-                <Link href={`/${param}/media`} className="w-full inline-flex items-center justify-center">
+                <Link href={`/${param}/media`} scroll={false} className="w-full inline-flex items-center justify-center">
                     <TabsTrigger value="media" className="w-full">
                         Media
                     </TabsTrigger>
                 </Link>
 
-                <Link href={`/${param}/likes`} className="w-full inline-flex items-center justify-center">
+                <Link href={`/${param}/likes`} scroll={false} className="w-full inline-flex items-center justify-center">
                     <TabsTrigger value="likes" className="w-full">
                         Likes
                     </TabsTrigger>
-- 
GitLab