Skip to content

Commit

Permalink
Merge pull request #91 from cloudflare/fix-user-leaving
Browse files Browse the repository at this point in the history
Send userLeft message when unmounting
  • Loading branch information
third774 authored Aug 19, 2024
2 parents 583792c + cf643bb commit 4fe866e
Showing 1 changed file with 11 additions and 4 deletions.
15 changes: 11 additions & 4 deletions app/hooks/useRoom.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { useEffect, useMemo, useState } from 'react'
import { useEffect, useMemo, useRef, useState } from 'react'
import type { ClientMessage, RoomState, ServerMessage } from '~/types/Messages'
import assertNever from '~/utils/assertNever'

Expand All @@ -14,6 +14,12 @@ export default function useRoom({
}) {
const [roomState, setRoomState] = useState<RoomState>({ users: [] })

const userLeftFunctionRef = useRef(() => {})

useEffect(() => {
return () => userLeftFunctionRef.current()
}, [])

const websocket = usePartySocket({
party: 'rooms',
room: roomName,
Expand Down Expand Up @@ -44,11 +50,12 @@ export default function useRoom({
},
})

userLeftFunctionRef.current = () =>
websocket.send(JSON.stringify({ type: 'userLeft' } satisfies ClientMessage))

useEffect(() => {
function onBeforeUnload() {
websocket.send(
JSON.stringify({ type: 'userLeft' } satisfies ClientMessage)
)
userLeftFunctionRef.current()
}
window.addEventListener('beforeunload', onBeforeUnload)
return () => {
Expand Down

0 comments on commit 4fe866e

Please sign in to comment.