-
Yusuf Akgül authoredYusuf Akgül authored
add-game-to-plan-list.tsx 2.68 KiB
"use client"
import { User } from "@prisma/client"
import { useRouter } from "next/navigation"
import { startTransition } from "react"
import { Button } from "./ui/button"
export default function AddGameToPlanList(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.planningGameList = props.user.planningGameList.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.planningGameList.push(gameId)
formData.planningGameList = props.user.planningGameList
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.planningGameList.includes(parseFloat(props.gameId))) {
button = (
<form onSubmit={addGame}>
<Button type="submit" size="lg" variant={"ghost"}>
Set as Planning
</Button>
</form>
)
} else {
button = (
<form onSubmit={removeGame}>
<Button type="submit" size="lg" variant={"ghost"}>
Unset Planning
</Button>
</form>
)
}
} catch (error) {
// throw new Error("Failed to check Planning-to-play-List");
}
return (
button
)
}