Skip to content

Commit

Permalink
unsubscribe from channels, register new players joining in
Browse files Browse the repository at this point in the history
  • Loading branch information
AlemTuzlak committed Dec 4, 2024
1 parent 5b79506 commit 906e178
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 4 deletions.
3 changes: 2 additions & 1 deletion app/realtime/player.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,8 @@ export const handlePlayerUpdate =
const data = queryClient.getQueryData<RoomLoaderData>(["room", roomId])!
if (!data.players.find((p) => p.playerId === newItem.player_id)) {
const data = await serverLoader()
queryClient.setQueryData(["room", roomId], data)

return queryClient.setQueryData(["room", roomId], data)
}
queryClient.setQueryData<typeof data>(["room", roomId], {
...data,
Expand Down
23 changes: 20 additions & 3 deletions app/routes/rooms.$roomId.tsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { useQuery } from "@tanstack/react-query"
import { QRCodeSVG } from "qrcode.react"
import { useEffect } from "react"
import { type LoaderFunctionArgs, redirect, useSubmit } from "react-router"
import { Grid } from "~/components/game/Grid"
import { Leaderboard } from "~/components/game/Leaderboard"
Expand Down Expand Up @@ -87,20 +88,28 @@ export const clientLoader = async ({ serverLoader, params }: Route.ClientLoaderA
queryClient.setQueryData(["room", params.roomId], data)
}
// Subscribe to real-time updates on the room
supabase
const roomSubscription = supabase
.channel("rooms")
.on("postgres_changes", { event: "*", schema: "public", table: "rooms" }, handleRoomUpdate(params.roomId))
.subscribe()
// Subscribe to real-time updates on the active players
supabase
const playerSubscription = supabase
.channel("active_players")
.on(
"postgres_changes",
{ event: "*", schema: "public", table: "active_players" },
handlePlayerUpdate(params.roomId, serverLoader)
)
.subscribe()
return data

const unsubscribe = () => {
roomSubscription.unsubscribe()
playerSubscription.unsubscribe()
}
return {
...data,
unsubscribe,
}
}

clientLoader.hydrate = true
Expand All @@ -109,6 +118,14 @@ export default function Room({ loaderData, params }: Route.ComponentProps) {
const { room, cards, user, qrCode } = loaderData
const submit = useSubmit()
const { data } = useQuery<Route.ComponentProps["loaderData"]>({ queryKey: ["room", params.roomId] })
// Close the channels when the user leaves the page
useEffect(() => {
return () => {
if ("unsubscribe" in loaderData) {
loaderData.unsubscribe()
}
}
}, [loaderData])
if (!data) return <div>Loading...</div>
const activeRoom = data.room
const activePlayers = data.players
Expand Down

0 comments on commit 906e178

Please sign in to comment.