refactor: create usePeerRoom hook

This commit is contained in:
Jeremy Kahn 2022-08-14 10:10:05 -05:00
parent 519e27b5c2
commit 53c4415112
4 changed files with 36 additions and 23 deletions

View File

@ -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}</>
}

View File

@ -0,0 +1 @@
export * from './usePeerRoom'

View File

@ -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,
}
}

View File

@ -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() {