fix: don't crash when the room changes

This commit is contained in:
Jeremy Kahn 2022-08-28 21:57:18 -05:00
parent 71ecc37d89
commit 39d8129957
2 changed files with 6 additions and 14 deletions

View File

@ -1,15 +1,16 @@
import { useEffect, useState } from 'react' import { useEffect, useState } from 'react'
import { RoomConfig } from 'trystero' import { RoomConfig } from 'trystero'
import { getPeerRoom } from 'services/PeerRoom' import { PeerRoom } from 'services/PeerRoom'
export function usePeerRoom(roomConfig: RoomConfig, roomId: string) { export function usePeerRoom(roomConfig: RoomConfig, roomId: string) {
const { appId } = roomConfig const [peerRoom] = useState(() => new PeerRoom(roomConfig, roomId))
const [peerRoom, setPeerRoom] = useState(getPeerRoom(roomConfig, roomId))
useEffect(() => { useEffect(() => {
setPeerRoom(getPeerRoom({ appId }, roomId)) return () => {
}, [appId, roomId]) peerRoom.leaveRoom()
}
}, [peerRoom])
return peerRoom return peerRoom
} }

View File

@ -1,5 +1,4 @@
import { joinRoom, Room, RoomConfig } from 'trystero' import { joinRoom, Room, RoomConfig } from 'trystero'
import memoize from 'fast-memoize'
export class PeerRoom { export class PeerRoom {
private room: Room private room: Room
@ -21,11 +20,3 @@ export class PeerRoom {
return this.room.makeAction<T>(namespace) 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)
})