Skip to content

Commit 0b33b53

Browse files
committed
fix: update useLiveKitRoom to only ever run room.connect / room.disconnect in series
Context around why this is important: #1197
1 parent 8453992 commit 0b33b53

File tree

1 file changed

+26
-11
lines changed

1 file changed

+26
-11
lines changed

packages/react/src/hooks/useLiveKitRoom.ts

Lines changed: 26 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
import { log, setupLiveKitRoom } from '@livekit/components-core';
22
import type { DisconnectReason } from 'livekit-client';
3-
import { Room, MediaDeviceFailure, RoomEvent } from 'livekit-client';
3+
import { Room, MediaDeviceFailure, RoomEvent, Mutex } from 'livekit-client';
44
import * as React from 'react';
55
import type { HTMLAttributes } from 'react';
66

@@ -126,6 +126,8 @@ export function useLiveKitRoom<T extends HTMLElement>(
126126
onDisconnected,
127127
]);
128128

129+
const connectDisconnectLock = React.useMemo(() => new Mutex(), []);
130+
129131
React.useEffect(() => {
130132
if (!room) return;
131133

@@ -155,20 +157,30 @@ export function useLiveKitRoom<T extends HTMLElement>(
155157
return;
156158
}
157159

158-
const connectionPromise = room.connect(serverUrl, token, connectOptions);
159-
(connectionSideEffect ? Promise.all([
160-
connectionPromise,
161-
connectionSideEffect,
162-
]) : connectionPromise).catch((e) => {
163-
log.warn(e);
164-
if (shouldConnect.current === true) {
165-
onError?.(e as Error);
160+
connectDisconnectLock.lock().then(async (unlock) => {
161+
try {
162+
const connectionPromise = room.connect(serverUrl, token, connectOptions);
163+
if (connectionSideEffect) {
164+
await Promise.all([connectionPromise, connectionSideEffect]);
165+
} else {
166+
await connectionPromise;
167+
}
168+
} catch (e) {
169+
log.warn(e);
170+
if (shouldConnect.current === true) {
171+
onError?.(e as Error);
172+
}
173+
} finally {
174+
unlock();
166175
}
167176
});
168177
} else {
169178
log.debug('disconnecting because connect is false');
170179
shouldConnect.current = false;
171-
room.disconnect();
180+
connectDisconnectLock.lock().then(async (unlock) => {
181+
await room.disconnect();
182+
unlock();
183+
});
172184
}
173185
}, [
174186
connect,
@@ -185,7 +197,10 @@ export function useLiveKitRoom<T extends HTMLElement>(
185197
if (!room) return;
186198
return () => {
187199
log.info('disconnecting on onmount');
188-
room.disconnect();
200+
connectDisconnectLock.lock().then(async (unlock) => {
201+
await room.disconnect();
202+
unlock();
203+
});
189204
};
190205
}, [room]);
191206

0 commit comments

Comments
 (0)