Skip to content

Commit

Permalink
Fix usePresence won't leave presence if unmount triggered during chan…
Browse files Browse the repository at this point in the history
…nel attaching

This fixes a race condition issue, where a React app might trigger a
component unmount while channel is still in the `attaching` state, thus
`presence.leave` was never called for a channel and member would remain
there until app reload.
  • Loading branch information
VeskeR committed Oct 4, 2024
1 parent 458c1ca commit 6151a9f
Showing 1 changed file with 5 additions and 3 deletions.
8 changes: 5 additions & 3 deletions src/platform/react-hooks/src/hooks/usePresence.ts
Original file line number Diff line number Diff line change
Expand Up @@ -73,9 +73,11 @@ export function usePresence<T = any>(
return () => {
// here we use the ably.connection.state property, which upon this cleanup function call
// will have the current connection state for that connection, thanks to us accessing the Ably instance here by reference.
// if the connection is in one of the inactive states or the channel is not attached, a presence.leave call will produce an exception.
// so we only leave presence in other cases.
if (channel.state === 'attached' && !INACTIVE_CONNECTION_STATES.includes(ably.connection.state)) {
// if the connection is in one of the inactive states or the channel is not attached/attaching, a presence.leave call will produce an exception.
// so we should only leave presence in other cases.
const canLeaveFromConnectionState = !INACTIVE_CONNECTION_STATES.includes(ably.connection.state);
const canLeaveFromChannelState = ['attached', 'attaching'].includes(channel.state);
if (canLeaveFromChannelState && canLeaveFromConnectionState) {
channel.presence.leave();
}
};
Expand Down

0 comments on commit 6151a9f

Please sign in to comment.