forked from Shiloh/remnantchat
refactor: create usePeerRoom hook
This commit is contained in:
parent
519e27b5c2
commit
53c4415112
@ -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}</>
|
||||
}
|
||||
|
1
src/hooks/usePeerRoom/index.ts
Normal file
1
src/hooks/usePeerRoom/index.ts
Normal file
@ -0,0 +1 @@
|
||||
export * from './usePeerRoom'
|
26
src/hooks/usePeerRoom/usePeerRoom.ts
Normal file
26
src/hooks/usePeerRoom/usePeerRoom.ts
Normal 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,
|
||||
}
|
||||
}
|
@ -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() {
|
||||
|
Loading…
Reference in New Issue
Block a user