diff --git a/lib/identity-search/identity-search-context.js b/lib/identity-search/identity-search-context.js --- a/lib/identity-search/identity-search-context.js +++ b/lib/identity-search/identity-search-context.js @@ -38,6 +38,10 @@ const socket = React.useRef(null); const heartbeatTimeoutID = React.useRef(); + const previousAuthMessage = React.useRef(authMessage); + const authMessageChanged = authMessage !== previousAuthMessage.current; + previousAuthMessage.current = authMessage; + const stopHeartbeatTimeout = React.useCallback(() => { if (heartbeatTimeoutID.current) { clearTimeout(heartbeatTimeoutID.current); @@ -53,7 +57,16 @@ }, identitySearchHeartbeatTimeout); }, [stopHeartbeatTimeout]); + const isSocketActive = + socket.current?.readyState === WebSocket.OPEN || + socket.current?.readyState === WebSocket.CONNECTING; + React.useEffect(() => { + if ((!authMessage || authMessageChanged) && isSocketActive) { + socket.current?.close(); + return; + } + if (connected || !authMessage) { return; } @@ -127,7 +140,14 @@ }; socket.current = identitySearchSocket; - }, [connected, authMessage, resetHeartbeatTimeout, stopHeartbeatTimeout]); + }, [ + connected, + authMessage, + resetHeartbeatTimeout, + stopHeartbeatTimeout, + authMessageChanged, + isSocketActive, + ]); const addListener = React.useCallback( (listener: IdentitySearchSocketListener) => {