diff --git a/src/components/Room/Room.tsx b/src/components/Room/Room.tsx index 18255bd..63618dc 100644 --- a/src/components/Room/Room.tsx +++ b/src/components/Room/Room.tsx @@ -1,28 +1,14 @@ -import { useEffect } from 'react' import { useParams } from 'react-router-dom' -import { PeerRoom } from '../../services/PeerRoom' +import { usePeerRoom } from '../../hooks/usePeerRoom' -interface RoomProps { - peerRoom?: PeerRoom -} +export function Room() { + const { roomId = '' } = useParams() -export function Room({ peerRoom = new PeerRoom() }: RoomProps) { - const params = useParams() - - const { roomId } = params - - useEffect(() => { - if (roomId) { - peerRoom.joinRoom(roomId) - } else { - console.error('roomId not specified') - } - - return () => { - peerRoom.leaveRoom() - } - }, [peerRoom, roomId]) + usePeerRoom({ + appId: process.env.REACT_APP_NAME || '', + roomId, + }) return <>Room ID: {roomId} } diff --git a/src/hooks/usePeerRoom/index.ts b/src/hooks/usePeerRoom/index.ts new file mode 100644 index 0000000..0ae1bf4 --- /dev/null +++ b/src/hooks/usePeerRoom/index.ts @@ -0,0 +1 @@ +export * from './usePeerRoom' diff --git a/src/hooks/usePeerRoom/usePeerRoom.ts b/src/hooks/usePeerRoom/usePeerRoom.ts new file mode 100644 index 0000000..de0b4af --- /dev/null +++ b/src/hooks/usePeerRoom/usePeerRoom.ts @@ -0,0 +1,26 @@ +import { useEffect, useMemo } from 'react' + +import { PeerRoom } from '../../services/PeerRoom' + +interface PeerRoomProps { + appId: string + roomId: string +} + +export function usePeerRoom({ appId, roomId }: PeerRoomProps) { + const peerRoom = useMemo(() => { + return new PeerRoom() + }, []) + + useEffect(() => { + peerRoom.joinRoom(appId, roomId) + + return () => { + peerRoom.leaveRoom() + } + }, [appId, peerRoom, roomId]) + + return { + peerRoom, + } +} diff --git a/src/services/PeerRoom/PeerRoom.ts b/src/services/PeerRoom/PeerRoom.ts index c8ef900..6840d97 100644 --- a/src/services/PeerRoom/PeerRoom.ts +++ b/src/services/PeerRoom/PeerRoom.ts @@ -3,8 +3,8 @@ import { joinRoom } from 'trystero' export class PeerRoom { room: any - joinRoom(roomId: string) { - this.room = joinRoom({ appId: process.env.REACT_APP_NAME }, roomId) + joinRoom(appId: string, roomId: string) { + this.room = joinRoom({ appId }, roomId) } leaveRoom() {