From 39d8129957bcc9d2511631d4678861ca379443c3 Mon Sep 17 00:00:00 2001 From: Jeremy Kahn Date: Sun, 28 Aug 2022 21:57:18 -0500 Subject: [PATCH] fix: don't crash when the room changes --- src/hooks/usePeerRoom/usePeerRoom.ts | 11 ++++++----- src/services/PeerRoom/PeerRoom.ts | 9 --------- 2 files changed, 6 insertions(+), 14 deletions(-) diff --git a/src/hooks/usePeerRoom/usePeerRoom.ts b/src/hooks/usePeerRoom/usePeerRoom.ts index 3752334..2e9b91b 100644 --- a/src/hooks/usePeerRoom/usePeerRoom.ts +++ b/src/hooks/usePeerRoom/usePeerRoom.ts @@ -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 } diff --git a/src/services/PeerRoom/PeerRoom.ts b/src/services/PeerRoom/PeerRoom.ts index d1051f3..8767f40 100644 --- a/src/services/PeerRoom/PeerRoom.ts +++ b/src/services/PeerRoom/PeerRoom.ts @@ -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(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) -})