Skip to content

Commit

Permalink
Merge pull request #1884 from ably/ECO-5002/fix-usePresence-channel-n…
Browse files Browse the repository at this point in the history
…ame-race-condition

[ECO-5002] Fix usePresence won't leave presence if unmount triggered during channel attaching
  • Loading branch information
VeskeR authored Oct 4, 2024
2 parents 458c1ca + 6151a9f commit 5bfb32f
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 5bfb32f

Please sign in to comment.