diff --git a/app/hooks/useRoom.ts b/app/hooks/useRoom.ts index 8edd4a23..f103b23c 100644 --- a/app/hooks/useRoom.ts +++ b/app/hooks/useRoom.ts @@ -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' @@ -14,6 +14,12 @@ export default function useRoom({ }) { const [roomState, setRoomState] = useState({ users: [] }) + const userLeftFunctionRef = useRef(() => {}) + + useEffect(() => { + return () => userLeftFunctionRef.current() + }, []) + const websocket = usePartySocket({ party: 'rooms', room: roomName, @@ -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 () => {