"use client" import { User } from "@prisma/client" import { useRouter } from "next/navigation" import { startTransition } from "react" import { Button } from "./ui/button" export default function AddGameToPlayingList(props: { gameId: string, user: User }) { const router = useRouter() const gameId = parseFloat(props.gameId) const user = props.user let formData: { id: String gameId: Number add: boolean planningGameList: number[] | undefined playingGameList: number[] | undefined finishedGameList: number[] | undefined } = { id: "", gameId: -1, add: true, planningGameList: undefined, playingGameList: undefined, finishedGameList: undefined } async function removeGame(e: any) { e.preventDefault() formData.id = user.id formData.playingGameList = props.user.playingGameList.filter((id) => id !== gameId) const response = await fetch('/api/users/gamelists', { method: 'PUT', body: JSON.stringify(formData) }) 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() } async function addGame(e: any) { e.preventDefault() formData.id = user.id props.user.playingGameList.push(gameId) formData.playingGameList = props.user.playingGameList const response = await fetch('/api/users/gamelists', { method: 'PUT', body: JSON.stringify(formData) }) 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() } let button = <div></div> try { if (!props.user.playingGameList.includes(parseFloat(props.gameId))) { button = ( <form onSubmit={addGame}> <Button type="submit" size="lg" variant={"ghost"}> Set as Playing </Button> </form> ) } else { button = ( <form onSubmit={removeGame}> <Button type="submit" size="lg" variant={"ghost"}> Unset Playing </Button> </form> ) } } catch (error) { // throw new Error("Failed to check playing-to-play-List"); } return ( button ) }