forked from Shiloh/remnantchat
fix: don't crash when the room changes
This commit is contained in:
parent
71ecc37d89
commit
39d8129957
@ -1,15 +1,16 @@
|
||||
import { useEffect, useState } from 'react'
|
||||
import { RoomConfig } from 'trystero'
|
||||
|
||||
import { getPeerRoom } from 'services/PeerRoom'
|
||||
import { PeerRoom } from 'services/PeerRoom'
|
||||
|
||||
export function usePeerRoom(roomConfig: RoomConfig, roomId: string) {
|
||||
const { appId } = roomConfig
|
||||
const [peerRoom, setPeerRoom] = useState(getPeerRoom(roomConfig, roomId))
|
||||
const [peerRoom] = useState(() => new PeerRoom(roomConfig, roomId))
|
||||
|
||||
useEffect(() => {
|
||||
setPeerRoom(getPeerRoom({ appId }, roomId))
|
||||
}, [appId, roomId])
|
||||
return () => {
|
||||
peerRoom.leaveRoom()
|
||||
}
|
||||
}, [peerRoom])
|
||||
|
||||
return peerRoom
|
||||
}
|
||||
|
@ -1,5 +1,4 @@
|
||||
import { joinRoom, Room, RoomConfig } from 'trystero'
|
||||
import memoize from 'fast-memoize'
|
||||
|
||||
export class PeerRoom {
|
||||
private room: Room
|
||||
@ -21,11 +20,3 @@ export class PeerRoom {
|
||||
return this.room.makeAction<T>(namespace)
|
||||
}
|
||||
}
|
||||
|
||||
// Memoization isn't just a performance optimization here. It is necessary to
|
||||
// prevent subsequent calls to getPeerRoom from causing a room collision due to
|
||||
// the amount of time it takes for Trystero rooms to be torn down (which is an
|
||||
// asynchronous operation that cannot be `await`-ed).
|
||||
export const getPeerRoom = memoize((config: RoomConfig, roomId: string) => {
|
||||
return new PeerRoom(config, roomId)
|
||||
})
|
||||
|
Loading…
Reference in New Issue
Block a user